开发者

jQuery: why doesn't programmatic radio button selection work?

开发者 https://www.devze.com 2023-02-11 03:21 出处:网络
My task is really simple: given the set of 4 radio buttons, I need to programmatically check/select one of it on a click on an image. As simple as that.

My task is really simple: given the set of 4 radio buttons, I need to programmatically check/select one of it on a click on an image. As simple as that.

Now I have these radio buttons:

<input type="radio" name="answer" value="A">
<input type="radio" name="answer" value="B">
<input type="radio" name="answer" value="C">
<input type="radio" name="answer" value="D">
开发者_如何学Python

The following jQuery code works just like a charm - when called from the click() function of an image:

$('input[name="answer"]').filter("[value='A']").attr("checked", true);

That is, the first of radio buttons is selected, everyone is happy. But as soon as I put the same line of code in the click() function of another image on the same page - it suddenly stops working! When I click that other image, I can see - for a split second! - that the right radio button is selected and then immediately cleared! Obviously, there's no code there operating on those radio buttons apart from this single line in image's click() function.

Please, save my sanity - could anyone please explain to me, how on Earth is that possible??? And, more importantly, how to fix that?


Saw your question unrelated to setting radio buttons but in jQuery 2.0.0 and the browser I am using (IE and Chrome) .attr does not work but .prop does:

$("#someControlNameOrFilter).prop("checked", true);


Maybe this post can help you: How to reset radiobuttons in jQuery so that none is checked

Your code works on jsfiddle : http://jsfiddle.net/DfLVs/

0

精彩评论

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