0

I'm trying to loop through radio buttons on a form and get their value to compare to another value. If the values are equal it will check the radio button.

The issue I'm having is that the loop only gets the value from the first radio button.

What can I do to have it loop through all the radio buttons?

radio buttons (get appended to the form)

<span class="radioVNC">
    <input type="radio" name="EventSet" value="VNC"/>VNC
</span>
<br>
<span class="radioOLV">
    <input type="radio" name="EventSet" value="OLV"/>OLV
</span>
<br>
<span class="radioAct">
    <input type="radio" name="EventSet" value="Activity"/>Activity
</span>

code

$(document).ready(function () {
    var curResType = $('input[title="ReservationType2"]').val();
    $('input:radio[name="EventSet"]').each(function () {
        var radioVal = $('input[name="EventSet"]').val()
        if (radioVal == curResType) {
            $(this).prop('checked', true);
        }
    });
});
2

Try this

$(document).ready(function () {
        var curResType = $('input[title="ReservationType2"]').val();
        $('input:radio[value="' + curResType + '"]').each(function () {
                $(this).prop('checked', true);
        });
});

Or you can altogether avoid looping

$(document).ready(function () {
        var curResType = $('input[title="ReservationType2"]').val();
        $("input[name=EventSet]").val([curResType]);
});
1

If you are using a radio button that means you will be able to select only one of them every time, so instead of looping them why dont you validate your condition when one of them is clicked? It would be easy and faster than looping and then checking any one of them

e.g.: $(function(){
         $("input[name='EventSet']").click(function(){
             if($(this).val()==yourValue)
              { $(this).prop('checked',true);}

          });
      });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.