324

I've looked at numerous other questions and found very simple answers, including the code below. I simply want to detect when someone changes the content of a text box but for some reason it's not working... I get no console errors. When I set a breakpoint in the browser at the change() function it never hits it.

$('#inputDatabaseName').change(function () { 
    alert('test'); 
});
<input id="inputDatabaseName">
  • 1
    just a couple of things to try: give the input a type="text" and make it a singleton element. – szeliga May 27 '11 at 13:42

10 Answers10

602

You can use the input Javascript event in jQuery like this:

$('#inputDatabaseName').on('input',function(e){
    alert('Changed!')
});

In pure JavaScript:

document.querySelector("input").addEventListener("change",function () {
  alert("Input Changed");
})

Or like this:

<input id="inputDatabaseName" onchange="youFunction();"
onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
clami219
  • 2,958
  • 1
  • 31
  • 45
Ouadie
  • 13,005
  • 4
  • 52
  • 62
  • 1
    Can't seem to find documentation for this event, but it works exactly the way I expect it to. Any idea where I can find the doc page? – Jorge Pedret Jul 09 '13 at 18:40
  • 3
    You can find it on the list of HTML5 events : http://www.w3schools.com/tags/ref_eventattributes.asp or here http://help.dottoro.com/ljhxklln.php – Ouadie Jul 10 '13 at 08:44
  • 9
    This solution is actually far better than using keyup. E.g. IE lets the user clear input field by clicking an X which does not trigger keyup. – Georg Dec 29 '13 at 13:24
  • 1
    This doesn't seem to work if the input is changed with JavaScript. – RobW Jan 29 '14 at 16:00
  • 11
    Closest solution so far, but still doesn't work when browser performs autofill on the textboxes. – Saumil Feb 02 '14 at 19:05
  • 1
    Since the point is to identify when the content of the input has *changed*, this should be the accepted answer. – PeteH Feb 03 '14 at 07:06
  • 3
    This is far better than the first answer. Ctrl, Shift keys all count as keyup. And the worst part is, if you type fast, several input would register as only one keyup event. – octref May 01 '14 at 16:01
  • why jQuery does not have an `input(handler)` method?, how to know all the events which I can use apart from http://api.jquery.com/category/events/ – JaskeyLam Feb 05 '15 at 03:14
  • You can use [jQuery .on()](http://api.jquery.com/on/) and here is all the **HTML events** that you can use http://www.w3schools.com/tags/ref_eventattributes.asp – Ouadie Feb 05 '15 at 08:40
  • this does not work if input value changed by code `$('#inputDatabaseName').val("hello world!")` – serge Feb 06 '19 at 12:59
  • 1
    I was using "keyup" instead of "input" and the function it was calling was running twice. Changing to "input" fixed it. – Hugh Seagraves Mar 25 '19 at 23:09
184

try keyup instead of change.

<script type="text/javascript">
   $(document).ready(function () {
       $('#inputDatabaseName').keyup(function () { alert('test'); });
   });
</script>

Here's the official jQuery documentation for .keyup().

bryanbraun
  • 3,025
  • 2
  • 26
  • 38
Scott Harwell
  • 7,457
  • 2
  • 28
  • 41
  • 1
    *sigh* I swear I tried that (after looking at this question: http://stackoverflow.com/questions/1443292/how-to-implement-onchange-of-input-type-text-with-jquery)... but apparently not because it works now! –  May 27 '11 at 13:43
  • 30
    change only fires when the element looses focus and keyup is fired when a key on the keyboard is released. – Declan Cook May 27 '11 at 13:45
  • 11
    what if the user pastes code using ctrl+v or by dragging a selected text with the mouse onto the #inputDatabaseName? How do you detect that? – Radu Simionescu Jul 25 '13 at 08:21
  • 5
    The main problem with this is it still does not take into account if the content actually changes. Only that a button was pressed – Metropolis Nov 01 '13 at 20:38
  • @Metropolis, you've seen my answer?? http://stackoverflow.com/a/23266812/3160597 – azerafati Jul 16 '14 at 07:28
121

Each answer is missing some points, so here is my solution:

$("#input").on("input", function(e) {
  var input = $(this);
  var val = input.val();

  if (input.data("lastval") != val) {
    input.data("lastval", val);

    //your change action goes here 
    console.log(val);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input">
<p>Try to drag the letters and copy paste</p>

The Input Event fires on Keyboard input, Mouse Drag, Autofill and Copy-Paste tested on Chrome and Firefox. Checking for previous value makes it detect real changes, which means not firing when pasting the same thing or typing the same character or etc.

Working example: http://jsfiddle.net/g6pcp/473/


update:

And if you like to run your change function only when user finishes typing and prevent firing the change action several times, you could try this:

var timerid;
$("#input").on("input", function(e) {
  var value = $(this).val();
  if ($(this).data("lastval") != value) {

    $(this).data("lastval", value);
    clearTimeout(timerid);

    timerid = setTimeout(function() {
      //your change action goes here 
      console.log(value);
    }, 500);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input">

If user starts typing (e.g. "foobar") this code prevents your change action to run for every letter user types and and only runs when user stops typing, This is good specially for when you send the input to the server (e.g. search inputs), that way server does only one search for foobar and not six searches for f and then fo and then foo and foob and so on.

azerafati
  • 18,215
  • 7
  • 67
  • 72
  • 1
    This was the first to work from about 6 I tried. Awesome. Thanks. – Enkode May 16 '15 at 08:25
  • Almost works on IE9: if you delete a character, it doesn't fire the event. Very good workaround though – Soma Dec 04 '15 at 13:29
  • @Soma, as others say "breaking IE is not a flaw it's a feature" ;) although IE is not continued anymore but if you have a fix for that let us know – azerafati Dec 04 '15 at 17:41
  • I know, but I had to do it for work :( As a matter of fact, I do : use `$("#input").focusout(function () {})`. When you click outside your input, the event is fired. Works on current version of Chrome and Firefox, and IE9 – Soma Dec 04 '15 at 22:44
  • 2
    @Soma, if that's the only way for IE to work you could use it my way with only changing this line `$("#input").on("input focusout",function(e){` – azerafati Dec 05 '15 at 10:46
  • what the 'e' argument ? – Dr. Ehsan Ali Aug 07 '18 at 10:53
  • @Ehsan, `e` stands for `event` which is the event object that jQuery passes to the callback functions. It is merely there out of habit and hasn't been used. You could remove it if you don't need it – azerafati Aug 08 '18 at 07:51
24

Text inputs do not fire the change event until they lose focus. Click outside of the input and the alert will show.

If the callback should fire before the text input loses focus, use the .keyup() event.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • `change` is working here : http://jsfiddle.net/g6pcp/ ; `keyup` alert after each key which is not a good way – xkeshav May 27 '11 at 13:47
  • 1
    @diEcho I think the alert is just an example to get his code working...not what he intends to do in the end. – Scott Harwell May 27 '11 at 13:50
  • @diEcho What Scott said, it was just for testing purposes. That's how I debug :D –  May 27 '11 at 14:06
  • @Scott please please please use a proper debugger rather than `alert()`. It will make debugging **so much easier.** – Matt Ball May 27 '11 at 14:08
14

onkeyup, onpaste, onchange, oninput seems to be failing when the browser performs autofill on the textboxes. To handle such a case include "autocomplete='off'" in your textfield to prevent browser from autofilling the textbox,

Eg,

<input id="inputDatabaseName" autocomplete='off' onchange="check();"
 onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />

<script>
     function check(){
          alert("Input box changed");
          // Things to do when the textbox changes
     }
</script>
Saumil
  • 2,521
  • 5
  • 32
  • 54
4

In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.

<input type="text"  id="bookdate">

$("#bookdate").datepicker({            
     onSelect: function (selected) {
         //handle change event here
     }
});
kmxr
  • 479
  • 4
  • 4
  • Using the same datepicker and needed the same thing, thanks! But it's still weird that input change cannot be detected as a change on – yenren Nov 27 '20 at 06:35
2

Try something like this, it always works.

$(function() {
    $("#my_input").on("change paste keyup", function() {
       alert($(this).val()); 
    });
});
ucMedia
  • 4,105
  • 4
  • 38
  • 46
0

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});
Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
Yoosaf Abdulla
  • 3,722
  • 4
  • 31
  • 34
0
$('#inputDatabaseName').change(function(){
    alert('Changed!')
});

Source

Darwin
  • 1,695
  • 1
  • 19
  • 29
-4

WORKING:

$("#ContentPlaceHolder1_txtNombre").keyup(function () {
    var txt = $(this).val();
        $('.column').each(function () {
            $(this).show();
            if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
                $(this).hide();
            }
        });
    //}
});
  • 1
    That looks like code for a different question... what is that stuff about uppercasing values and showing / hiding content about? – Nico Haase Jan 23 '18 at 15:21
  • @NicoHaase I don't know why but you make me laugh so much. This answer and your comment made my day. – the_nuts Jun 30 '22 at 19:40