Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior with preventDefault() and radio buttons

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?

like image 467
Nathan Friend Avatar asked Apr 12 '12 05:04

Nathan Friend


1 Answers

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.

like image 122
Zeta Avatar answered Sep 28 '22 10:09

Zeta