How do you trigger a blur/focusout event on an input text box using jquery?
Asked Answered
P

3

5

I'm using 1.7.2 in which I understand 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");
}

The input box is appended, grabs focus and then the javascript console tells me:

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

I'd be grateful if anyone knows how I can catch the blur/focusout event.

Phrenetic answered 2/6, 2012 at 12:24 Comment(0)
B
4

You are accessing the DOM element with [0] and acting like it is a jQuery object.

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

cell.children().eq(0).focus().on("blur", function() {
    alert("blur");
};
Banket answered 2/6, 2012 at 12:29 Comment(0)
S
4

You should bind delegate event ie. live event to those inputs, because they appended to DOM later, so they need live event handler.

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

then trigger like following:

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

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

according to your code

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

or

cell.children(':input:first').focus().on("blur", function() {
    alert("blur");
};
Stadiometer answered 2/6, 2012 at 12:28 Comment(0)
B
4

You are accessing the DOM element with [0] and acting like it is a jQuery object.

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

cell.children().eq(0).focus().on("blur", function() {
    alert("blur");
};
Banket answered 2/6, 2012 at 12:29 Comment(0)
H
0

You are calling .on on a DOM element, not jQuery object, try this:

var input = $("<input/>", { "type": "text", val: content } );
cell.append(input);
input.focus();
input.on( "blur", function(){
    alert( "blur" );
});
Hardener answered 2/6, 2012 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.