简体   繁体   中英

Why radio button click event behaves differently

Example on JS FIddle .

The question is:

If the first click is on the radio button, it behaves normally; But if the first click is on span text (ie aaaa), it can not get the checked radio.

Please tell me why and how I can make it the same.

This code, which happens when the radio button is clicked:

var obj = $(e.target||e.srcElement).parent();
score = obj.find('input:checked').val();

Puts the parent in the obj variable, which is the containing DIV. This contains both of the radio buttons. It then finds the FIRST checked input element in that DIV, which is always the one with the 'first' value after it is checked.

You should just get the value of the item which was clicked:

score = $(e.target||e.srcElement).val();

This can be rewritten as

score = $(this).val();

Here's a working example: http://jsfiddle.net/RPSwD/10/

See new fiddle .

The problem is this line:

score = obj.find('input:checked').val();

Change it to:

score = $(this).val();

The reason for this is that you're looking for the selected item in the div but on the first click, the item has yet to become selected. Given that the event is targeted at the radio button, you can assume that radio is the selected one.

Note also that you don't need to use e.target||e.srcElement . jQuery takes care of this for you. Use $(this) instead.

Additionally, you need to set a name on the radio buttons to stop both from becoming selected. Alternatively, if having both selected is desired behaviour, use check boxes instead.

You don't need to use any of the event properties:

var score = $(this).val(); // in your '.x' click handler

$('.y').click(function(e) {
    $(this).prev('.x').click();
});

just wrap your radio button inside label tag like this

<label for="radio1">
   <input type=radio class="x" id="radio1" value="First"/>
   <span class="y">aaaa</span>
</label>

No need for extra jquery or javascript

check the demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM