Detect changed input text box
Asked Answered
A

11

328

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">
Achorn answered 27/5, 2011 at 13:41 Comment(1)
just a couple of things to try: give the input a type="text" and make it a singleton element. <input id="inputDatabaseName" type="text"/>Sisera
S
608

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();"/>
Shumate answered 29/3, 2013 at 16:3 Comment(11)
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?Offset
You can find it on the list of HTML5 events : w3schools.com/tags/ref_eventattributes.asp or here help.dottoro.com/ljhxklln.phpShumate
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.Ashwin
This doesn't seem to work if the input is changed with JavaScript.Hornpipe
Closest solution so far, but still doesn't work when browser performs autofill on the textboxes.Stopple
Since the point is to identify when the content of the input has changed, this should be the accepted answer.Nelidanelie
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.Boffa
why jQuery does not have an input(handler) method?, how to know all the events which I can use apart from api.jquery.com/category/eventsJokjakarta
You can use jQuery .on() and here is all the HTML events that you can use w3schools.com/tags/ref_eventattributes.aspShumate
this does not work if input value changed by code $('#inputDatabaseName').val("hello world!")Sepal
I was using "keyup" instead of "input" and the function it was calling was running twice. Changing to "input" fixed it.Perjury
G
185

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().

Gnu answered 27/5, 2011 at 13:42 Comment(5)
sigh I swear I tried that (after looking at this question: #1443792)... but apparently not because it works now!Achorn
change only fires when the element looses focus and keyup is fired when a key on the keyboard is released.Bruges
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?Harrar
The main problem with this is it still does not take into account if the content actually changes. Only that a button was pressedAramen
@Metropolis, you've seen my answer?? https://mcmap.net/q/81489/-detect-changed-input-text-boxKirwan
K
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.

Kirwan answered 24/4, 2014 at 10:52 Comment(7)
This was the first to work from about 6 I tried. Awesome. Thanks.Autolycus
Almost works on IE9: if you delete a character, it doesn't fire the event. Very good workaround thoughDonelladonelle
@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 knowKirwan
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 IE9Donelladonelle
@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){Kirwan
what the 'e' argument ?Milkweed
@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 itKirwan
U
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.

Unitarianism answered 27/5, 2011 at 13:42 Comment(4)
change is working here : jsfiddle.net/g6pcp ; keyup alert after each key which is not a good waySniper
@diEcho I think the alert is just an example to get his code working...not what he intends to do in the end.Gnu
@diEcho What Scott said, it was just for testing purposes. That's how I debug :DAchorn
@Scott please please please use a proper debugger rather than alert(). It will make debugging so much easier.Unitarianism
S
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>
Stopple answered 2/2, 2014 at 19:39 Comment(0)
W
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
     }
});
Warmblooded answered 15/6, 2015 at 20:32 Comment(1)
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 <select> can be detected.Nildanile
T
3

Try something like this, it always works.

$(function() {
    $("#my_input").on("change paste keyup", function() {
       alert($(this).val()); 
    });
});
Thirtythree answered 24/3, 2021 at 14:56 Comment(0)
A
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;
  }
});
Atlantis answered 6/2, 2014 at 13:29 Comment(0)
E
0
$('#inputDatabaseName').change(function(){
    alert('Changed!')
});

Source

Eba answered 10/4, 2022 at 9:20 Comment(0)
H
0

$(document).on('input', '#inputDatabaseName', function () { alert("yess"); });

Harleyharli answered 8/10, 2023 at 7:35 Comment(1)
Please leave some explanation. Also you code block when you include code snippet.Pyrography
D
-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();
            }
        });
    //}
});
Detainer answered 23/1, 2018 at 14:59 Comment(2)
That looks like code for a different question... what is that stuff about uppercasing values and showing / hiding content about?Siam
@NicoHaase I don't know why but you make me laugh so much. This answer and your comment made my day.Lavernalaverne

© 2022 - 2024 — McMap. All rights reserved.