Aflred
Aflred

Reputation: 4603

input field "onchange" event jquery

<input type="text" id="myinput" name="myinput" value="" />

how do i use jquery to detect the "onchange" event of the input field.I tried everything but nothing seems to fire it.

$("#myinput").bind("onchange",alert("test"));
$("#myinput").change(alert("test"));

im using jquery 2.03.Its the "onchange" aka once the user finishes typing then fire event.Not fire after each letter changed, because im getting json from the server and it would cause a tremendous load if it where to call on each letter change.

as paul said this is the solution i guess..thx alot

http://jsfiddle.net/kerc6/5/

Upvotes: 2

Views: 6021

Answers (3)

Rajesh Paul
Rajesh Paul

Reputation: 7019

If you expect it to fire on each keypress then you are wrong. It will automatically fire when the focus is out of the element.

It occurs instantly only for elements like radio-button, checkbox.

For your specific purpose define jquery event input as follows:

$("input").on('input', function(){alert(1)});

N.B. this works only for textual input elements for instant change detection. Most importantly, it detects any type of change i.e. through either keyboard or mouse

Fiddle

Upvotes: 2

user2509485
user2509485

Reputation: 219

By using keyup down you can also track it:

  <script>
   $(document).ready(function(){
   $("#myinput").keydown(function(){
    $("#myinput").css("background-color","yellow");
   });
   $("#myinput").keyup(function(){
    $("#myinput").css("background-color","pink");
   });
 });
</script>

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

Use the .on() method, create a function handler and do stuff inside.

jQuery(function( $ ){ // DOM is now ready

    $("#myinput").on("input", function(){ // or use "change" if you need
      // DO SOMETHING
    });

});

The other way:

function inputChangeStuff(){
    // DO SOMETHING
}

jQuery(function( $ ){ // DOM is now ready    
    $("#myinput").on("input", inputChangeStuff);     
});

Upvotes: 3

Related Questions