开发者

Why .change works only when I select an element?

开发者 https://www.devze.com 2023-03-16 09:50 出处:网络
I have this code : Yes <input type=\"radio\" value=\"txt1\" name=\"myRadio\" id=\"text1\" checked=true />

I have this code :

Yes <input type="radio" value="txt1" name="myRadio" id="text1" checked=true />
No <input type="radio" value="txt2" name="myRadio" id="text2" />

$('#text1').change(function() {
    alert('changed');
    return;
});

that handler only the id=text1 (yeah, I should do this on the name). But it should works anyway. In fact it works only when I select the checkbox te开发者_如何学编程xt1, not when I select text2.

Why? And how can I fix this?


Wrap the inputs in a div. Right now, you're only referencing the first input.

<div id="container">
Yes <input type="radio" value="txt1" name="myRadio" id="text1" checked=true />
No <input type="radio" value="txt2" name="myRadio" id="text2" />
</div>

$('#container input').click(function() {
    alert('changed');
    return;
});


this works only on text1 cause your event is attached only to the element with the id = text1. How else do u want it to work. Yes you have to use the name "myRadio" to make it work on both.


The previous answer given to wrap it in a div changes the page layout. If you need to do this without affecting the page then you can select the radio element by name:

$('input[name="myRadio"]').change(function() {
    alert('changed');
    return;
});
0

精彩评论

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