Search code examples
jqueryradio-button

jquery get value of group of radio buttons


this is my html code:

<form name="dform">
<fieldset>
    <input type="radio" class="yes" name="g1" value="1"/> Yes<br/>
    <input type="radio" class="no" name="g1" value="0"/> No
</fieldset>
    <fieldset>
   <input type="radio" class="yes" name="g2" value="1"/> Yes<br/>
        <input type="radio" class="no" name="g2" value="0"/> No
    </fieldset>
    <fieldset>
    <input type="radio" class="yes" name="g3" value="1"/> Yes<br/>
        <input type="radio" class="no" name="g3" value="0"/> No
    </fieldset>
    <input type="reset" class="reset" value="RESET"/><BR/>
</form>
<div id="result">N/A</div>

i would like to set the value like this:

  1. If yes gets 3, result will be "Low"
  2. If yes gets 2 score, result will be "Medium"
  3. If no gets 3 or 2 score, result will be "High"
  4. No check for any radio button will show "N/A"
  5. 1 score for each yes and no will also show "N/A"

and I've tried my jquery script like this:

function scoring(){
        var score_yes = 0;
        var score_no = 0;
        $(".yes:checked").each(function()){
            score_yes += parseInt ($(this).val());
        });

        $(".no:checked").each(function(){
            score_no += parseInt ($(this).val());
        });

        if($(score_yes)==3){
            $("#result").html('LOW');
        }else if($(score_yes)==2){
            $("#result").html('MEDIUM');
        }else if(($(score_no)==3){
            $("#result").html('HIGH');
        }else if($(score_no)==2){
            $("#result").html('HIGH');
        }else{
            $("#result").html('N/A');
        }
    }
$(document).ready(function(){
    $(".yes:checked").change(function(){
        scoring();
    });
 });

but it didn't work. What should I fix?


Solution

  • There were many issues from extra parenthesis in a couple places to wrapping an int in a jquery object ($(score_yes) for example) to binding on .yes:checked (I believe you want .yes, .no as both those would change the #result). There was also a bit of simplification you could do. I believe this is what you want:

    fiddle

    function scoring() {
        var score_yes = $(".yes:checked").size();
        var score_no = $(".no:checked").size();
    
        if (score_yes == 3) {
            $("#result").html('LOW');
        } else if (score_yes == 2) {
            $("#result").html('MEDIUM');
        } else if (score_no == 3) {
            $("#result").html('HIGH');
        } else if (score_no == 2) {
            $("#result").html('HIGH');
        } else {
            $("#result").html('N/A');
        }
    }
    $(document).ready(function () {
        $(".yes, .no").change(function () {
            scoring();
        });
    });