Sum of Radio button values printed to the user

Viewed 129

I'm very new to html.

I have a survey with two questions where the question choices are presented with radio buttons as this html code shows:

<form>
    <p id="description">1. Question 1?</p>
    <p>
        <label><input type="radio" name="q1" value="5" /> Yes</label>
        <label><input type="radio" name="q1" value="0" /> No</label>
    </p>
    <p id="description">2. Question 2?</p>
    <p>
        <label><input type="radio" name="q2" value="5" /> Yes</label>
        <label><input type="radio" name="q2" value="0" /> No</label>
    </p>
</form>

I want to print to the user the sum of his two selections.

So the output could be "You score is 10." if he answered yes to both questions etc.

How can I do this in the simplest way with the code being on the same page as the html code above? Is that possible?

2 Answers

var question1Answers = document.getElementsByName('q1');
var question2Answers = document.getElementsByName('q2');
var answer = 0;

question1Answers.forEach((e) => {
    if (e.checked) {
        answer += e.value;
        break;
    }
});

question2Answers.forEach((e) => {
    if (e.checked) {
        answer += e.value;
        break;
    }
});

console.log(answer);

please try this:

$("input[type='button']").click(function () {
  var score = getChecklistItems();
  alert("You score is : " + score);
});

function getChecklistItems() {
  var total_score = 0
  var result = $("input:radio:checked").get();
  var checked_value = $.map(result, function (element) {
    return $(element).attr("value");
  });
  for (i = 0; i < checked_value.length; i++) {
    total_score += parseInt(checked_value[i])
  }
  return total_score
}
<form>
  <p id="description">1. Question 1?</p>
  <p>
    <label><input type="radio" name="q1" value="5" /> Yes</label>
    <label><input type="radio" name="q1" value="0" /> No</label>
  </p>
  <p id="description">2. Question 2?</p>
  <p>
    <label><input type="radio" name="q2" value="5" /> Yes</label>
    <label><input type="radio" name="q2" value="0" /> No</label>
  </p>
  <p><input type="button" value="Submit"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related