views:

31

answers:

2

Here's my HTML code:

<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

+2  A: 

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.

Rowno
Thanks !! This solved my problem :)
Yvan JANSSENS
+1  A: 

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();
Donny Kurnia
Corrected that too :)
Yvan JANSSENS