207

<select> has this API. What about <input>?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
omg
  • 136,412
  • 142
  • 288
  • 348

14 Answers14

283

As @pimvdb said in his comment,

Note that change will only fire when the input element has lost focus. There is also the input event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text.

(See documentation.)

This is so useful, it is worth putting it in an answer. Currently (v1.8*?) there is no .input() convenience fn in jquery, so the way to do it is

$('input.myTextInput').on('input',function(e){
 alert('Changed!')
});
Richard
  • 56,349
  • 34
  • 180
  • 251
iPadDeveloper2011
  • 4,560
  • 1
  • 25
  • 36
  • 6
    Particularly, IE<9 does not support at all. – dlo Apr 04 '13 at 00:04
  • 18
    Since you can bind to multiple events `$('form').on('change input', function);` did the trick for me. Thanks. – pyronaur Jul 05 '13 at 09:50
  • 12
    @Norris. That will probably fire twice when an element is changed (1st), and loses focus (2nd). That is not a problem for many purposes, but is worth noting nevertheless. – iPadDeveloper2011 Oct 13 '13 at 01:34
  • Tested at IE9, backspace will not be fired – JaskeyLam Jul 01 '15 at 09:15
  • Note, this will fire for every input change made (which might be what you're looking for). But, if you're looking for an event like "When done changing", [here's a great example](http://stackoverflow.com/a/4220182/5667951). – Trevor Nestman Dec 08 '16 at 16:00
246

You can use .change()

$('input[name=myInput]').change(function() { ... });

However, this event will only fire when the selector has lost focus, so you will need to click somewhere else to have this work.

If that's not quite right for you, you could use some of the other jQuery events like keyup, keydown or keypress - depending on the exact effect you want.

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 1
    Unfortunately, this doesn't work for a hidden input. A possible solution when required a onchange on a hidden input is: (with css).. – NickGreen Aug 11 '11 at 07:19
  • 323
    Note that `change` will only fire when the input element has lost focus. There is also the `input` event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text. – pimvdb Aug 25 '12 at 10:23
  • 4
    Great comment @pimvdb. I used this, and turned it into an answer to this question. – iPadDeveloper2011 Sep 27 '12 at 00:30
  • 1
    As I am trying this, and have just learned that the event only fires when two conditions are met: 1) value change; and 2) blur, I wonder if what many people expect of change() is better handled by keyup() ? – TARKUS Dec 21 '13 at 16:59
  • As `change` isn't supported by IE9, you can use `focusout` to have the same comportment – Soma Dec 04 '15 at 22:45
  • The note on losing focus is what helped me .. . . – Andrew Jan 16 '17 at 20:48
89

I would suggest using the keyup event something like below:

$('elementName').keyup(function() {
 alert("Key up detected");
});

There are a few ways of achieving the same result so I guess it's down to preference and depends on how you want it to work exactly.

Update: This only works for manual input not copy and paste.

For copy and paste I would recommend the following:

$('elementName').on('input',function(e){
 // Code here
});
Andrew
  • 9,967
  • 10
  • 64
  • 103
38

Here's the code I use:

$("#tbSearch").on('change keyup paste', function () {
    ApplyFilter();
});

function ApplyFilter() {
    var searchString = $("#tbSearch").val();
    //  ... etc...
}

<input type="text" id="tbSearch" name="tbSearch" />

This works quite nicely, particularly when paired up with a jqGrid control. You can just type into a textbox and immediately view the results in your jqGrid.

Mike Gledhill
  • 27,846
  • 7
  • 149
  • 159
27

There is one and only one reliable way to do this, and it is by pulling the value in an interval and comparing it to a cached value.

The reason why this is the only way is because there are multiple ways to change an input field using various inputs (keyboard, mouse, paste, browser history, voiceinput etc.) and you can never detect all of them using standard events in a cross-browser environment.

Luckily, thanks to the event infrastructure in jQuery, it’s quite easy to add your own inputchange event. I did so here:

$.event.special.inputchange = {
    setup: function() {
        var self = this, val;
        $.data(this, 'timer', window.setInterval(function() {
            val = self.value;
            if ( $.data( self, 'cache') != val ) {
                $.data( self, 'cache', val );
                $( self ).trigger( 'inputchange' );
            }
        }, 20));
    },
    teardown: function() {
        window.clearInterval( $.data(this, 'timer') );
    },
    add: function() {
        $.data(this, 'cache', this.value);
    }
};

Use it like: $('input').on('inputchange', function() { console.log(this.value) });

There is a demo here: http://jsfiddle.net/LGAWY/

If you’re scared of multiple intervals, you can bind/unbind this event on focus/blur.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • Is is possible to make your code work like this: `$('body').on('inputchange', 'input', function() { console.log(this.value) });`? Or not, as is mentioned here: https://github.com/EightMedia/hammer.js/pull/98 ? – TheFrost Aug 17 '13 at 02:51
  • 15
    Writing and launching such a code is a madness with extreme performance impact. – Danubian Sailor Aug 29 '13 at 09:59
  • @ŁukaszLech Please, tell me about it. But if you hit the focus/blur events as I also mentioned, the interval will only run temporarely. Surely, even an intel 386 from 1988 can handle a single interval? – David Hellsing Aug 29 '13 at 15:22
6
<input id="item123" class="firstName" type="text" value="Hello there" data-someattr="CoolExample" />

$(".firstName").on('change keyup paste', function () {
   var element = $(this);
   console.log(element);
   var dataAttribute = $(element).attr("data-someattr");
   console.log("someattr: " + dataAttribute );
});

I recommend use this keyword in order to get access to the entire element so your are able do everything you need with this element.

NoWar
  • 36,338
  • 80
  • 323
  • 498
6

If you want to trigger the event as you type, use the following:

$('input[name=myInput]').on('keyup', function() { ... });

If you want to trigger the event on leaving the input field, use the following:

$('input[name=myInput]').on('change', function() { ... });
Usman Ahmed
  • 2,392
  • 1
  • 20
  • 17
  • For some reason this didn't work for me, but this did: `$(document).on('change', 'input[name=myInput]', function() { ... });` – Stefan Jun 10 '20 at 14:29
  • 1
    @Stefan, the code in your example is called event delegation. Your input fields must have been adding up after the page initialization, that's why my code didn't work for you. – Usman Ahmed Jun 10 '20 at 16:30
5

The following will work even if it is dynamic/Ajax calls.

Script:

jQuery('body').on('keyup','input.addressCls',function(){
  console.log('working');
});

Html,

<input class="addressCls" type="text" name="address" value="" required/>

I hope this working code will help someone who is trying to access dynamically/Ajax calls...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vinith
  • 1,264
  • 14
  • 25
3
$("input").keyup(function () {
    alert("Changed!");
});
Phu
  • 572
  • 3
  • 10
3
$("input").change(function () {
    alert("Changed!");
});
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
3

You can do this in different ways, keyup is one of them. But i am giving example below with on change.

$('input[name="vat_id"]').on('change', function() {
    if($(this).val().length == 0) {
        alert('Input field is empty');
    }
});

NB: input[name="vat_id"] replace with your input ID or name.

Rokan Nashp
  • 331
  • 4
  • 13
2

You could simply work with the id

$("#your_id").on("change",function() {
    alert(this.value);
});
damirstuhec
  • 6,069
  • 1
  • 22
  • 39
Nerdy Sid
  • 332
  • 5
  • 14
1

This worked for me. If field with name fieldA is clicked or any key entered it updates field with id fieldB.

jQuery("input[name='fieldA']").on("input", function() {
    jQuery('#fieldB').val(jQuery(this).val());
});
Seefan
  • 230
  • 3
  • 9
0

You could use .keypress().

For example, consider the HTML:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there" />
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the input field:

$("#target").keypress(function() {
  alert("Handler for .keypress() called.");
});

I totally agree with Andy; all depends on how you want it to work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kcho0
  • 169
  • 1
  • 1
  • 7
  • 1
    This doesn't work for copy/paste operations. No event is fired if text is pasted in with a mouse click. – DaveN59 Jun 12 '14 at 21:40