How can I bind an OnChange event of a TextBox to function using jQuery?
Am trying this and its failing:
$(document).ready(function() {
$("input#tags").bind("change",autoFill);
});
function autoFill() {
$("#tags").autocomplete("/taglookup/", {
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator:",",
scroll: true,
scrollHeight: 300,
delay: 10
});
}
NB: I want to implement a Tag TextBox like the one for stackoverflow which detects OnChange events and calls AJAX functions when a user types in.
Combination of keyup
and change
is not necessarily enough (browser's autocomplete and paste using mouse also changes the contents of a text box, but doesn't fire either of these events):
You must change the event name from "change" to "onchange":
$(document).ready(function(){
$("input#tags").bind("onchange", autoFill);
});
or use the shortcut binder method change:
$(document).ready(function(){
$("input#tags").change(autoFill);
});
Note that the onchange event usually fires when the user leave the input, so for auto-complete you better use the keydown event.
if you're trying to use jQuery autocomplete plugin, then I think you don't need to bind to onChange event, it will
You're looking for keydown/press/up
$("#inputID").keydown(function(event) {
alert(event.keyCode);
});
or using bind $("#inputID").bind('onkeydown', ...
Here's a clue why an onchange() call might not fire your bound function:
I 2nd Chad Grant's answer and also submit this blog article [removed dead link] for your viewing pleasure.
What Chad says, except its better to use .keyup in this case because with .keydown and .keypress the value of the input is still the older value i.e. the newest key pressed would not be reflected if .val() is called.
This should probably be a comment on Chad's answer but I dont have privileges to comment yet.
Source: Stackoverflow.com