Strange behavior with preventDefault() and radio buttons
Asked Answered
C

1

12

See this jsFiddle:

http://jsfiddle.net/nathanfriend/vAcpc/9/

It seems that the preventDefault() method doesn't prevent the clicked radio button from toggling (notice that the message always says "This radio button was checked", regardless of its prior state). However, after the onclick() method finishes, the radio buttons snap back to their initial states (except for the very first time a radio button is selected).

It seems like preventDefault() works not by actually preventing the radio button from being checked, but rather by just returning the set of buttons to their prior state. Can anyone explain this behavior? I'd like to be able to completely prevent the radio button from ever being toggled - this way I could accurately check to see if the radio button was checked inside its onclick() method. Any ideas?

Czarism answered 12/4, 2012 at 5:47 Comment(0)
O
12

Actually a mousedown event will get fired first and check your radio button. You can easily verify this by holding the mouse button on a radio button. However, almost all GUI elements only get executed or changed if both mousedown and mouseup are fired and successfully run.

See this example (demo):

$(function() {
    $('[name="test"]').each(function() {
         $(this).mousedown(function(e) {
            e.preventDefault();
            if ($(this).is(':checked')) {
                alert('This radio button was checked in mousedown');                
            } else {
                alert('This radio button was not checked in mousedown');
            }                    
        });
        $(this).click(function(e) {
            e.preventDefault();
            if ($(this).is(':checked')) {
                alert('This radio button was checked');
            } else {
                alert('This radio button was not checked');
            }                    
        });
    });           
});

As you can see the mousedown gets fired first, and it will alert 'This radio button was not checked in mousedown'. The click event is prevented because the actually mouseup event gets canceled by the nasty alert. However, if you use console.log you'll notice that click is still executed and the radio button is still checked virtually.

However, if you check for active radio buttons you'll notice that none is active. The behavior of click element is sometimes irritating, but e.preventDefault() will do it's job, don't worry.

Og answered 12/4, 2012 at 5:54 Comment(2)
You can compare it on Safari 7 and Chrome 33. The results are different and I am facing issues for the same.Triggerfish
@swapnil0545: This answer is almost two years old. Post a new question to draw more attention.Og

© 2022 - 2024 — McMap. All rights reserved.