104

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); 
}
0

16 Answers 16

154

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

Sign up to request clarification or add additional context in comments.

7 Comments

Does not work for detecting change after user pastes from clipboard
That just fixed my problem. I prefer onkeyup though, for it gets the new value in the input ('element.value')
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).
'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!)
Since this is the accepted answer, can we change the onkeypress solution to oninput
|
54

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/

8 Comments

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.
Too late for a comment but... Why do you suggest use jQuery if the answering user shows plain JavaScript?
@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 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ésMorales Note my answer covers "paste, keyup, etc". I recall the jQuery solution being convenient when I answered this question (7 years ago!).
|
35

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

1 Comment

works with type="number" spinner control too (which onkeypress doesn't work with).
28

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.

5 Comments

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?
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.
@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?
So sad that it comes to this.
@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.
17

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

Comments

11

use following events instead of "onchange"

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

Comments

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); 
}

Comments

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'));
});

Comments

1

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

1 Comment

what when a value is pasted ? I use "onpaste" to trigger the event too
1

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

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

Comments

1

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.

Comments

1

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.

Comments

1

I have been facing the same issue until I figured out how to do it. You can utilize a React hook, useEffect, to write a JS function that will trigger after React rendering.

useEffect(()=>{
    document.title='fix onChange with onkeyup';
    const box = document.getElementById('changeBox');
    box.onkeyup = function () {
        console.log(box.value);
    }
},[]);

Note onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input and that's why we have used onkeyup menthod. In the functional component where you have the <Input/> for the <form/>write this

<form onSubmit={handleLogin} method='POST'>
                    <input 
                    aria-label= 'Enter Email Address'
                    type='text'
                    placeholder='Email Address'
                    className='text-sm text-gray-base w-full mr-3 py-5 px-4 h-2 border border-gray-primary rounded mb-2'
                    
                    id='changeBox'
                    
                    />
                    
                </form>

Resulting Image : Console Image

Comments

0

Use below code:

document.getElementById("num1").addEventListner('input' e => {
//write your logic
})

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0
 <input type="text" oninput={(event=>{console.log(event)}}  /> 

so use oninput The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.

Comments

-3

try onpropertychange. it only works for IE.

1 Comment

Why would anyone want to consider a property that only works in an OBSOLETE BROWSER that has been abandoned by its developer? Downvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.