2

I have a text field <input type="text" id="search" /> and I would like to execute a JavaScript function every time the user change the content in it (letter by letter). How can I do this using jQuery?

I tried to implement the function as the answer to Using JQuery, how do you detect if the value of a text input has changed while the field still has focus? but nothing happens for me.

Here is my HTML:

<html>
<head>
<script type="text/javascript" src="/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="/search.js"></script>
</head> 
<body> 
<form>
<input type="text" name="search" id="search" /> 
</form>
</body> 
</html>

My search.js is:

var target = $('#search'), val = target.val();

function search()
{
    alert('search');
}

target.keyup(search);

I have also tried with (nothing happens):

$('input[name=search]').change(function() {
    alert('changed');
})

And if I try just adding some HTML using jQuery, it works:

$(function(){
    $("<p>hello</p>").insertAfter("#search");
})
Community
  • 1
  • 1
Jonas
  • 121,568
  • 97
  • 310
  • 388
  • 1
    The element has id `search`, not `itemsearch`, and you always have to put the code inside `$(function(){...})` if you want to access DOM elements. – Felix Kling May 25 '11 at 11:58

1 Answers1

3

The change event doesn't fire until the control loses focus. If you are only interested in text, you can use .keypress() to do something before the contents change, or .keyup() to do something afterwards.

Here is an example using keypress in jsfiddle: http://jsfiddle.net/R6vmZ/

verdesmarald
  • 11,646
  • 2
  • 44
  • 60