Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery, how do you detect if the value of a text input has changed while the field still has focus?

I noticed prior to posting this question that there have been similar questions posted on this topic before, however the user isn't interacting with the text field by using the keyboard in this instance, in such case binding the text field to the "Paste" action or any of the other nifty suggestions wouldn't work in my case.

Our users are inputting a string value that is scanned in from a Bar Code. What we're attempting to do is to avoid the annoyance of having the user put the scanner down to go to the next field after scanning in the information. However, I'm having an issue detecting the change in value of a text field while it still has focus.

This is the only part of the puzzle that we're missing, because to apply focus to the next field on the form is trivial. Can anyone shed light on how to detect a change in value of a text field when the input device is NOT the keyboard? I've already tried using the change() event but it doesn't fire until the field no longer has focus.

like image 739
Will Madison Avatar asked Oct 08 '09 17:10

Will Madison


People also ask

How do you detect change in text input box?

Answer: Use the input Event You can bind the input event to an input text box using on() method to detect any change in it. The following example will display the entered value when you type something inside the input field.

How do you know if input field is focused?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.


1 Answers

You can just listen for the keypress event.

<input type="text" id="target" value="" />

var target = $('#target'),
    val = target.val();

function monitor()
{
    var current_val = $(this).val();
    if (current_val != val) {
        console.log('changed from', val, 'to', current_val);
        val = current_val;
    }
}

target.keypress(monitor);
like image 133
slikts Avatar answered Oct 24 '22 19:10

slikts