90

I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchange event property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.

index.php

<script type="text/javascript" src="javascript.js"> </script>

<form action="index.php" method="get">
 Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
 Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
 <input type="submit" value="Compute" />
</form>

javascript.js

function checkInput(textbox) {
 var textInput = document.getElementById(textbox).value;

 alert(textInput); 
}
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Newbie Coder
  • 9,534
  • 18
  • 38
  • 51

13 Answers13

133

onchange is only triggered when the control is blurred. Try onkeypress instead.

Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283
  • 20
    Does not work for detecting change after user pastes from clipboard – Juozas Kontvainis Sep 18 '13 at 11:19
  • 19
    That just fixed my problem. I prefer `onkeyup` though, for it gets the new value in the `input` ('element.value') – stealthjong Sep 11 '14 at 09:37
  • 4
    I also notice "keypress" doesn't get raised after pressing backspace, at least when using jquery. "keyup" does get raised after pressing and releasing backspace. "input" solves this problem and also works for copy-paste, and I think this is the proper solution here (as user "99 Problems - Syntax ain't one" points out below). – Patrick Finnigan May 24 '16 at 14:41
  • 5
    'onkeypres', 'onkeyup', etc. is not a solution when one wants to call a function only if *the text has changed*! Key events produce an unnecessary traffic in this case. (Very strange that this reply has been chosen as a solution, esp. with so meny votes!! I don't downvote it, because I don't like to just downvote replies. I prefer to give the reason(s) why it's not OK - It's more helpful!) – Apostolos Sep 10 '17 at 01:56
  • For HTML ≥5 or jQuery ≥1.7 there are other solutions below, which also handles pasting from clipboard. – user202729 Nov 02 '18 at 12:55
  • @Apostolos does have a point. But all of these suggestions still falls short when you are working with an autocomplete list for instance, and the user completes the input by selecting an option. What eventually works in my case is onblur. Either the user types the input and leaves the control manually or he uses the mouse to auto complete an entry, onblur catches both. – Seun S. Lawal Dec 01 '18 at 11:16
  • Since this is the accepted answer, can we change the `onkeypress` solution to `oninput` – David Callanan Nov 04 '19 at 21:21
45

Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

For static and dynamic inputs:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

rybo111
  • 10,836
  • 3
  • 55
  • 62
  • 1
    This worked perfectly for me - thanks. Note for others - don't forget to actually execute the above code in your onLoad or something for it to 'begin' monitoring. – Robert Penridge Jan 03 '14 at 16:55
  • Too late for a comment but... Why do you suggest use jQuery if the answering user shows plain JavaScript? – Andrés Morales Feb 06 '20 at 13:03
  • @AndrésMorales It's a common library that many applications have immediate access to, and is simple to add to those that don't. Obviously, this answer does not apply to those applications that cannot (or choose not to) use jQuery. – rybo111 Feb 06 '20 at 14:18
  • @rybo111 Exactly! jQuery is a common library and widely used, but it directly links in my brain to the meme question about "sum two numbers using JavaScript" and the most upvoted reply about using jQuery to do it. It's not the case but many people can't separate JavaScript and jQuery. – Andrés Morales Feb 07 '20 at 16:06
  • @AndrésMorales Note my answer covers "paste, keyup, etc". I recall the jQuery solution being convenient when I answered this question (7 years ago!). – rybo111 Feb 07 '20 at 18:50
  • If you are stuck with an old jQuery version, you can use `.live` instead of `.on`. – holmis83 Oct 15 '20 at 15:06
30

Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.

Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().

Let's say that your input field has an id and name of "city":

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

Have a global variable named "city":

var city = "";

Add this to your page initialization:

setInterval(lookForCityChange, 100);

Then define a lookForCityChange() function:

function lookForCityChange()
{
    var newCity = document.getElementById("city").value;
    if (newCity != city) {
        city = newCity;
        doSomething(city);     // do whatever you need to do
    }
}

In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.

If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.

Dragonfly
  • 770
  • 7
  • 11
  • 1
    If it's not possible to change the value of an input field without it getting focus and a blur occurs when an element loses focus, why not just look for changes in onblur? – Pakman Aug 19 '14 at 18:51
  • Do you want to take action when the input field changes, or when it loses focus after a change? If you want to act immediately, you can't wait for the onblur. – Dragonfly Oct 14 '14 at 03:37
  • @Pakman That's a decent solution in some cases. But if you want to do search-as-you-type - a very nice feature IMO (why should the user have to look for stuff when the computer can do it so much faster and without being bored?) - or anything else really that needs to happen when the text changes, why shouldn't you be able to? – The Dag Aug 20 '15 at 09:51
  • So sad that it comes to this. – Chuck Batson Jan 20 '16 at 00:34
  • 1
    @ChuckBatson This answer is from 2012. I noticed you posted your comment in 2016. See my answer if you're using jQuery, it's incredibly easy now. – rybo111 Jul 21 '16 at 08:54
26

HTML5 defines an oninput event to catch all direct changes. it works for me.

Soufiane ELH
  • 505
  • 5
  • 8
  • 1
    works with type="number" spinner control too (which onkeypress doesn't work with). – Bob Mar 04 '19 at 18:31
13

onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.

if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc

Read more about the change event here

Read more about the input event here

11

use following events instead of "onchange"

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
metaforce
  • 1,257
  • 3
  • 16
  • 26
6

Firstly, what 'doesn't work'? Do you not see the alert?

Also, Your code could be simplified to this

<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />

function checkInput(obj) {
    alert(obj.value); 
}
Ash Burlaczenko
  • 21,581
  • 14
  • 63
  • 95
2

I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event

$('.inputClassToBind').bind('textchange', function (event, previousText) {
    alert($(this).attr('id'));
});
James Moberg
  • 4,047
  • 1
  • 20
  • 19
2

A couple of comments that IMO are important:

  • input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.

  • The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input

  • The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)

  • Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...

  • jQuery has nothing to do with this. This is all in HTML standard.

  • If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.

My two cents.

cancerbero
  • 5,662
  • 1
  • 26
  • 18
1

onkeyup worked for me. onkeypress doesn't trigger when pressing back space.

Bishnu Paudel
  • 2,013
  • 1
  • 20
  • 38
1

It is better to use onchange(event) with <select>. With <input> you can use below event:

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Bhavin Patel
  • 73
  • 2
  • 5
0

when we use onchange while you are typing in input field – there’s no event. But when you move the focus somewhere else, for instance, click on a button – there will be a change event

you can use oninput

The oninput event triggers every time after a value is modified by the user.Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.

<input type="text" id="input"> oninput: <span id="result"></span>
<script>
  input.oninput = function() {
    console.log(input.value);
  };
</script>

If we want to handle every modification of an <input> then this event is the best choice.

Belhadjer Samir
  • 1,019
  • 2
  • 11
-3

try onpropertychange. it only works for IE.

jack jiao
  • 19
  • 1
  • 6
    Why would anyone want to consider a property that only works in an OBSOLETE BROWSER that has been abandoned by its developer? Downvote. – Sod Almighty Mar 16 '16 at 21:17