Wilfred Hughes
Wilfred Hughes

Reputation: 31151

jQuery's .live() ignoring events

Given the following snippet of HTML:

    Goggles <input type="checkbox" id="id_goggles_opt_in" name="goggles_opt_in">
    Approved <input type="checkbox" id="id_approved" name="approved">

and this JavaScript:

$('#id_approved').live('click', function() {
    alert('click is fine when selected by ID');
});

var $formInputs = $('.form input[type=text], .form input:file, .form textarea, .form select, .form input[type=checkbox]');

var $checkboxes = $formInputs.filter('[type=checkbox]');
console.log("This selector actually finds the elements: " + $checkboxes.size());
console.log($checkboxes)

$checkboxes.live('click', function() {
    alert('bizarrely this is never called');
});

The second alert is never fired. #jquery regulars advised me to just use .delegate, but why doesn't this work?

Example on JSFiddle: http://jsfiddle.net/amA3h/

Upvotes: 1

Views: 126

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

Mully is right -- using .filter() interferes with the .live() event.

This works:

var $checkboxes = $('.form input[type=checkbox]');
$checkboxes.live('click', function() {
    alert('bizarrely this is never called');
});

http://jsfiddle.net/mblase75/amA3h/5/

Or, to do it .delegate-style:

$('.form').delegate('input:checkbox','click', function() {
    alert('bizarrely this is never called');
});

Upvotes: 3

Xyan Ewing
Xyan Ewing

Reputation: 912

From jQuery's documentation:

DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector...

Upvotes: 5

Related Questions