tomK
tomK

Reputation: 31

How to select Radio button using JQuery

I have created group of radio buttons using <c:forEach> tag. I have given ids also.

On click of any radio button i do a ajax call. Once i come back to that page i want to re select that radio button.

For this i assign back selected radio button ID to a hidden text box.

My question is how to make radio button selected with this hidden text box value.

I tried like

$('input[id="$("#myHiddenTextBoxId").val()"]').attr('checked', true);

But it is not working. Here myHiddenTextBoxId hold value of previously selected radio button.

Upvotes: 2

Views: 3055

Answers (3)

Manse
Manse

Reputation: 38147

You where sending it all as a string - you need to split it out

$(document).ready(function() {
   $('input[id="' + $("#myHiddenTextBoxId").val() + '"]').prop('checked',true);
});

prop() should be used as of jQuery 1.6 -> http://api.jquery.com/prop/

Note Also ensure that your code is enclosed within the $(document).ready() function to ensure that the DOM is ready before trying to manipulate it.

Upvotes: 3

Didier Ghys
Didier Ghys

Reputation: 30676

Try this:

$('input[id="' + $("#myHiddenTextBoxId").val() + '"]').prop('checked', true);

You cannot have a jquery function call ($("#myHiddenTextBoxId").val()) in the selector string.

Working example here.


Note:

Use .attr() this way: .attr('checked', 'checked')
Although, for special attributes like checked or disabled, use .prop('checked', true) (jquery 1.6+)

Upvotes: 1

Tadeck
Tadeck

Reputation: 137450

$('#myHiddenTextBoxId').prop('checked', true);

Upvotes: 1

Related Questions