How do you trigger a blur / focus event in an input text box using jquery?

I am using 1.7.2 in which I understand that this should work:

// cell is a jquery representation of a <td> element
cell.append($("<input/>", { "type": "text" }).val(content));        
cell.children()[0].focus();
cell.children()[0].on("blur", function() {
    alert("blur");
}

An input field is added, captures focus, and then the javascript console tells me:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'on'

I would appreciate it if anyone knows how I can catch the blur / focusout event.

+5
source share
3 answers

You access the DOM element with [0]and act as if it were a jQuery object.

If you want only the first, you need to use eq()to get a jQuery object.

cell.children().eq(0).focus().on("blur", function() {
    alert("blur");
};
+4
source

, .. , DOM , .

$(cell).on('blur focusout', ':text', function() {
   alert(this.value);
});

:

$(':input:first', cell).blur(); // or $(':text', cell).trigger('blur');

$(':input:first', cell).focusout(); // or $(':text', cell).trigger('focusout');.

cell.children(':input:eq(0)').focus().on("blur", function() {
    alert("blur");
};

cell.children(':input:first').focus().on("blur", function() {
    alert("blur");
};
+4

You are calling .onin a DOM element, not a jQuery object, try the following:

var input = $("<input/>", { "type": "text", val: content } );
cell.append(input);
input.focus();
input.on( "blur", function(){
    alert( "blur" );
});
0
source

All Articles