开发者

Radioboxes and JQuery

开发者 https://www.devze.com 2022-12-18 18:02 出处:网络
Here\'s my HTML code: 开发者_StackOverflow中文版<label><input type=\"radio\" id=\"fNuttig\" /> Nuttig</label>

Here's my HTML code:

开发者_StackOverflow中文版<label><input type="radio" id="fNuttig" /> Nuttig</label>
<label><input type="radio" id="fNietNuttig" /> Niet nuttig</label>
<label><input type="radio" id="fNogUitTeMakenNuttig" />Nog uit te maken</label>

And here's my javascript code:

if ($('#fNuttig').val() == 'on') {
 nuttig = 'Nuttig';
} else if ($('#fNietNuttig').val() =='on') {
 nuttig = 'Niet nuttig';
} else if ($('#fNogUitTeMakenNuttig').val() =='on') {
 nuttig = 'Nog uit te maken';
} else {
 nuttig = 'ongeldige invoer';
}
alert($('#fNuttig').val()); // Gives 'on'
alert($('#fNietNuttig').val());  // Gives 'on'
alert($('#fNogUitTeMakenNuttig').val());  // Gives 'on'
alert(nuttig);  // Gives 'on'

This code gets called when pressing a button.

Why are all my radiobuttons turned on? If I add the 'name=' tag, and accomplish the same using PHP, it does work, and in javascript, it says that my buttons are always 'on'.

What am I doing wrong?

Yvan


You want to use if ( $('#fNuttig').is(':checked') ) instead of if ( $('#fNuttig').val() == 'on' ).

$('#fNuttig').val() is just retrieving the value of the value attribute, whether it's checked or not. $('#fNuttig').is(':checked') will return true if it's checked and false if it's not.


Your HTML code lack of name attribute. It's mandatory for a input element to have them. Radios with same name will only able to turn on one of it. any particular reason why you write the js code like the above?

It's better to access it by name

<input name="radio" .../>

$('input[name="radio"]').val();
0

精彩评论

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

关注公众号