Bastian Albers

Dezember 21, 2009

Setting radio button values with jQuery

Abgelegt unter: Uncategorized — Tags:, , — Bastian Albers @ 3:48 pm

Let’s say you have a group of radio buttons on your page:

<input type="radio" checked="checked" value="1" name="rayray"/>
<input type="radio" value="2" name="rayray"/>
<input type="radio" value="3" name="rayray"/>

Now getting the value of the selected radio button is easy with jQuery:

$("input[name='rayray']:checked").val();

You have to use the name attribute, as there are several different radio buttons with the same name. Now setting the value to the third option is a bit tricky, but this works for me:

$("input[name='rayray']").each(function(i) {
	if(i==2)
		$(this).attr('checked', true);
	else
		$(this).attr('checked', false);
});

If anyone has a quicker, more elegant way: feel free to share!

(This is all valid for jquery 1.32)

Powered by WordPress ( WordPress Deutschland )