Search code examples
javascriptradio-buttonradiobuttonlist

Displaying radio button value total


I am working on an interactive checklist that needs to count how many "yes" and "no" answers the user has selected and display the total either in an alert box or on a page. A yes answer gets a value of 1, and a no gets a value of 0.

The problem is, when I am clicking the total button, it is displaying the value of each answer and then the total - I just need it to display the total.

I have poked around SO for solutions, and I have modified my code based on what I have already found. I am pretty new to javascript, so I must be missing something.

Here is the code:

    <script type="text/javascript"><!--
    $(document).ready(function () {
    $('input:radio').on('change',function(){
    var $first_question = parseInt($("input[name=first_answer]:checked").val());
    var $second_question = parseInt($("input[name=second_answer]:checked").val());
    $first_question = $first_question? $first_question : 0; 
    $second_question = $second_question? $second_question : 0;

    var $total_score = $first_question + $second_question;


   {
   $("#btn").click(function() {
   alert($total_score);
   });
   };

   });
   });
   //--></script>

And here is my HTML:

    <p id="first_question">First Question<input name="first_answer" class="styled"    type="radio" value="1" /><!-- POSITIVE ANSWER -->Yes <input name="first_answer" class="styled" type="radio" value="0" /><!-- NEGATIVE ANSWER -->No</p>
    <p id="second_question">second question <input name="second_answer" class="styled" type="radio" value="1" /><!-- POSITIVE ANSWER -->Yes <input name="second_answer" class="styled" type="radio" value="0" /><!-- NEGATIVE ANSWER -->No</p>
    <input id="btn" type="button" value="See total" /> <input type="reset" value="Reset" /></body>

Solution

  • Is this what you want?

    var $total_score = 0;
    
    $(document).ready(function () {
        $('input:radio').on('change',function(){
            var $first_question = parseInt($("input[name=first_answer]:checked").val());
            var $second_question = parseInt($("input[name=second_answer]:checked").val());
            $first_question = $first_question? $first_question : 0; 
            $second_question = $second_question? $second_question : 0;
            $total_score = $first_question + $second_question;
        });
    
       $("#btn").click(function() {
           alert($total_score);
        });
    
    });
    

    If it is, your error was that you added an event to the click button every time the radio button changes value.