jquery radio值始终返回0

时间:2014-12-21 06:12:51

标签: javascript jquery

我想获得所选单选按钮的值

HTML

<form id='formTeacherOptions' method='post' target='_self' action='static.php'>       
    <div id='subjectoptions'>
        <input name='radioGrpSbjOption' type='radio' value='0' /> View Subject <br />
        <input name='radioGrpSbjOption' type='radio' value='1' /> Update Subject <br />            
     </div>
     <div id='testoption'>
        <input name='radioGrpSbjOption' type='radio' value='2' /> Create Test 
        <div id='testoptionsubjects'> </div>
        <div id='testoptiontopic'> </div>

        <br />
        <input name='radioGrpSbjOption' type='radio' value='3' /> View/Update Test <br />
        <input name='radioGrpSbjOption' type='radio' value='4' /> Activated Test <br />
     </div>
     <div id='reportoptions'>
        <input name='radioGrpSbjOption' type='radio' value='5' /> Quiz Report <br />
        <input name='radioGrpSbjOption' type='radio' value='6' /> Exam Report <br />
     </div>
     <button id='' type='button'> Submit </button>
  </form>

JS

$('input[name="radioGrpSbjOption"]').bind('change', function (){
   alert ($('input[name="radioGrpSbjOption"]').val());
})

返回的值始终为0.我的代码有什么问题?

3 个答案:

答案 0 :(得分:4)

使用:checked选择器

   alert ($('input[name="radioGrpSbjOption"]:checked').val());

答案 1 :(得分:1)

$('input[name="radioGrpSbjOption"]').bind('change', function (){
   alert ($(this).val());
})

<强> JS Fiddle

答案 2 :(得分:1)

您的代码$('input[name="radioGrpSbjOption"]')找到所有无线电并返回第一个值为0的值。所以将代码更改为:

$('input[name="radioGrpSbjOption"]').bind('change', function (){
    alert ($('input[name="radioGrpSbjOption"]:checked').val());
});

它使用:checked选择器以name="radioGrpSbjOption"

查找所选输入

jsFiddle Demo