我有一个简单的2个单选按钮,如果选中它们,我需要获取它们的值。
<form class="descriptions" id="collection" method="post" action="">
<table width="200">
<tr>
<td>
<label>Collection</label>
<input type="radio" value="collection" name="collection" />
</td>
<td>
<label>Delivery</label>
<input type="radio" value="delivery" name="collection" />
</td>
</tr>
</table>
</form>
var delivery = "";
delivery = $('input:radio:checked').val();
if(delivery == 'delivery') {
meal_deal7 = 11.49;
}else {
meal_deal7 = 9.99
}
meal_deal7的值总是9.99, 我做错了。
感谢
答案 0 :(得分:6)
您需要将代码放在附加到每个单选按钮的事件处理程序中,以便每次单击/选中单选按钮时更新delivery
变量的值
Working Demo - 添加 / edit 以查看代码并播放示例。
代码
$("input:radio[name='collection']").click(function() {
var delivery = $("input:radio[name='collection']:checked").val();
if(delivery == 'delivery') {
meal_deal7 = 11.49;
}
else {
meal_deal7 = 9.99
}
});
我很想使用CSS类来识别radiobuttons
答案 1 :(得分:1)
请看以下示例link提供的礼物 并对表单进行必要的更改;
<form name="orderform">
Which one is your favorite?<br>
<input type="radio" name="music" value="Rock"
checked="checked"> Rock<br>
<input type="radio" name="music" value="Reggae"> Reggae<br>
<input type="radio" name="music" value="Pop"> Pop<br>
<input type="radio" name="music" value="Rap"> Rap<br>
<input type="radio" name="music" value="Metal"> Metal<br>
<input type="submit" onclick="get_radio_value()">
</form>
答案 2 :(得分:0)
使用javascript获取值
var elemArray=document.getElementsByName('collection');
var value="";
if(elemArray.length>0){
for(var i=0;i<elemArray.length;i++){
if(elemArray.checked==true){
value=elemArray.value;
}
}
}else{
if(elemArray.checked==true){
value=elemArray.value;
}
}