whoasked
whoasked

Reputation: 420

$("#selector").click vs. onchange

Edited as several folks pointed out I'd mixed onchange and onclick ...

I posted this question yesterday, which someone kindly answered in a way that fixed my problem, but I don't quite get why the $("#selector").click methon works but the onchange=(...) doesn't.

So if I have HTML, in parent element DataTable cloumn header, where any click in header fires DataTable sort routine:

<div>
    <input type="checkbox" id="select_all" onchange="SelectAll(event)">
    SELECT ALL
</div>
//This is hit only AFTER the sort routine from the parent element is fired.
function SelectAll(event) {
    event.stopPropagation();

    var boxes = document.querySelectorAll("[name*=\"include_\"]");  //All checkboxes prefixed "include_".       
    var chk = document.getElementById('select_all').checked;

    for (var i = 0; i < boxes.length; i++) {
        if(!boxes[i].disabled) {
            boxes[i].checked = chk;
        }
    }
}

//This is hit BEFORE the sort routine from the parent element is fired.
$("#select_all").click(function(event){
    event.stopPropagation()
});
} 

The second method, fired before the parent element's click event, works for me, but what is the underlying difference between the two?.

JsFiddle

Upvotes: 1

Views: 1053

Answers (3)

Michael Geary
Michael Geary

Reputation: 28860

If you're going to use jQuery, just use it. Why do you want to mix up old-school "onxxxx" attributes with this?

Your code is really simple. Just do this instead:

<div>
    <input type="checkbox" id="select_all">
    SELECT ALL
</div>

function SelectAll( event ) {
    event.stopPropagation();

    var chk = $('#select_all')[0].checked;
    $("[name*=\"include_\"]").each( i, element ) {
        if( ! element.disabled ) {
            element.checked = chk;
        }
    }
}

$("#select_all").click( SelectAll );

Upvotes: 0

Jordi Flores
Jordi Flores

Reputation: 2150

onChange event is usually fired when element loses focus, so Click event will be fired first.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

In the onchange logic you're providing the global event object, which is not available in all browsers and is also not 100% guaranteed to be the click event you expect.

For this reason it's best to avoid on* event attributes and use an unobtrusive event handler in either native JS or jQuery - exactly as your second JS example is doing. The event object passed to the handler function is guaranteed to be the relevant event that contains the information you require.

Also note that the jQuery logic is using a click event handler, not a change. You should change the .click() to a .change() so that the event handler still works for those who navigate the web via the keyboard.

Upvotes: 2

Related Questions