2015-04-17 170 views
2

我想要在jQuery中检查单选按钮的值。但它返回值为'未定义'。我搜索了这个问题的解决方案,但没有为我工作。jQuery .val()返回undefined的单选按钮

我的HTML代码。

<label><input type="radio" class="service" name="service" id="all-service" value="all-service"> All Service</label><br> 
<label><input type="radio" class="service" name="service" id="electrician" value="Electrician"> Electrician</label><br> 
<label><input type="radio" class="service" name="service" id="painter" value="Painter"> Painter</label><br> 
<label><input type="radio" class="service" name="service" id="photo and video coverage" value="Photo and Video Coverage"> Photo and Video Coverage</label> 

我的jQuery代码..

$(document).ready(function() { 
    $(".service").change(function() { 
     alert($(".service :checked").val()); 
    }); 
}); 

这里fiddle我的问题..

+5

删除多余的空格应该是' “服务:检查”'。空间意味着你通过后代搜索。 – Regent

回答

7

不应该有类名和属性:checked之间的任何空间

$(".service").change(function() { 
     alert($(".service:checked").val()); 
    }); 

Fiddle

+1

哎呀..!粗心的错误..非常感谢.. – Mdumanoj

4
$(document).ready(function() { 
    $(".service").change(function() { 
     alert($(this).val()); 
    }); 
}); 

Link to Fiddle

+1

这是更好的方法 –

+1

如果它没有选中然后呢?我thnk用户只需要选定的值。 – nirmal

+0

@nirmal在这种情况下,你不能不勾选它而不检查另一个按钮。 AFAIK,你不能在没有JavaScript的帮助下取消收音机。 –

0

bewteen .service:

alert($(".service:checked").val());