开发者

Getting checked state of a radiobutton

I am trying to get the checked state of a radiobutton using jQuery without much luck.

My HTML looks like:

<div class="fr">
        <label>
            Recieve Email Updates?</label>

         Yes
            <input type="radio" value="True" name="ConsumerModel.RecieveSMS" id="ConsumerModel_RecieveSMS" data-val-required="The RecieveSMS field is required." data-val="true">
            No
            <input type="radio" value="False" name="ConsumerModel.RecieveSMS" id="ConsumerModel_RecieveSMS" checked="checked">
    </div>
<div class="fr">
        <label>
            Recieve Email Updates?</label>

         Yes
            <input type="radio" value="True" name="ConsumerModel.RecieveEmail" id="ConsumerModel_RecieveEmail" data-val-required="The RecieveEmail field is r开发者_运维技巧equired." data-val="true" checked="checked">
            No
            <input type="radio" value="False" name="ConsumerModel.RecieveEmail" id="ConsumerModel_RecieveEmail">
    </div>

My jQuery looks like:

  var sms= $('input[name=ConsumerModel.RecieveSMS]:checked').val();
  var email = $('input[name=ConsumerModel.RecieveEmail]:checked').val();

My variable sms seems to be ok however email is always the same as sms even if the 2 are different.

What am I doing wrong?


Because you dont have unique names/ids your code breaks.

Check the live sample.

Basically $("input[name=...]:checked") returns two elements rather then one.

<div class="fr">
    <label>
        Recieve Email Updates?</label>

    Yes
    <input type="radio" value="True" name="ConsumerModel.RecieveSMS" class="ConsumerModel_RecieveSMS" data-val-required="The RecieveSMS field is required." data-val="true">
    No
    <input type="radio" value="False" name="ConsumerModel.RecieveSMS" class="ConsumerModel_RecieveSMS" checked="checked">
</div>
<div class="fr">
    <label>
        Recieve Email Updates?</label>

    Yes
    <input type="radio" value="True" name="ConsumerModel.RecieveEmail" class="ConsumerModel_RecieveEmail" data-val-required="The RecieveEmail field is required." data-val="true" checked="checked">
    No
    <input type="radio" value="False" name="ConsumerModel.RecieveEmail" class="ConsumerModel_RecieveEmail">
</div>

If you change the id to a class which does not need to be unique then it works.

Live example


$('input:radio').is('checked');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜