简体   繁体   中英

radio button checked property not setting when preventDefault is also used

The problem I am having is that the radio buttons in my scenario are not being selected when they are clicked. I have created a JSFiddle to show the code and the issue.

For whatever reason, I have an entire area that is surrounded in an element.

<a href="/link">
    //some stuff
    <div class="protected">
        <input type="radio" name="b1" value="1" /> Button 1
        <input type="radio" name="b1" value="2" /> Button 2
    </div>
    //some stuff
</a>

There is a small section within this tag that needs to be protected from the default behaviour of the link. This section contains some radio inputs which need to be selectable.

The way I currently have it, I am protecting the "protected" section with an event listener and:

$('.protected').off('click').on('click', function (e) {
    e.preventDefault();
});

I also have an event listener on the radio buttons so that I can perform the change of property when they are clicked.

$('.protected > :radio').off('click').on('click', function (e) {
    $(this).siblings(':radio').removeAttr('checked');
    $(this).attr('checked', 'checked');
});

Unfortunately, this is setting the checked attribute in the dom however the radio button is not being filled in on the screen for the user.

Any help would be greatly appreciated.

You need to add stopPropagation()

$('.protected > :radio').off('click').on('click', function (e) {
    e.stopPropagation();

    //$(this).siblings(':radio').removeAttr('checked');
    //$(this).attr('checked', 'checked');
});

Also, make sure to comment out

$(this).siblings(':radio').removeAttr('checked');
$(this).attr('checked', 'checked');

You don't need them as the browser handles this for you.

DEMO

What was happening is, since you had preventDefault in the container click handler, the nested click event was propagating to that click handler and was preventing the radio button from being set.

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