将单选按钮值传递给Javascript

时间:2013-03-13 19:00:19

标签: javascript jquery

这是我的HTML

<tr>
    <td class="g">
    Gender
    </td>
    <td class="g_input">
        <input type="radio" name="gender" id="settings_gender" value="Male" checked />&nbsp;&nbsp;Male &nbsp;&nbsp;&nbsp;
    <input type="radio" name="gender" id="settings_gender" value ="Female" />&nbsp;&nbsp;Female
    </td>
</tr>

这是javascript

$(document).ready(function () {
    $(".update-basic-info").click(function () {
        var gender = $("#settings_gender").val();

        alert(gender);
    });
});

输出仅显示男性,当我检查女性单选按钮时,它仍显示男性

2 个答案:

答案 0 :(得分:5)

ID在您的网页上应该是唯一的。您可以使用类或名称属性

来完成
var gender = $('input[name=gender]:checked').val();

或将ID更改为类

<input type="radio" name="gender" class="settings_gender" value="Male" checked />&nbsp;&nbsp;Male &nbsp;&nbsp;&nbsp;
<input type="radio" name="gender" class="settings_gender" value ="Female" />&nbsp;&nbsp;Female

var gender = $(".settings_gender:checked").val();

工作jsFiddle:http://jsfiddle.net/TvVFM/

答案 1 :(得分:0)

$('input[name=gender]').click(function(){
     alert($(this).val());
});

或将两个单选按钮的类别设置为“settings_gender”并尝试此

$('.settings_gender').click(function(){
     alert($(this).val());
});