85
votes

I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

<input type="text" id="name" onchange="checkLength(this.value)" />

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this? I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

7
You could use onkeyup and onchange? - James Allardice
The only issue I have is that browser's autocompleter selection would not cause any of these events to occur. - Sachin Midha
What kind of input field is this? - powtac
oh...I forgot to add it into the sample code, its a text field. - Sachin Midha
I thought this would have been a very common issue & lots of people would have faced it, but now it seems the other way round...:) - Sachin Midha

7 Answers

123
votes
(function () {
    var oldVal;

    $('#name').on('change textInput input', function () {
        var val = this.value;
        if (val !== oldVal) {
            oldVal = val;
            checkLength(val);
        }
    });
}());

This will catch change, keystrokes, paste, textInput, input (when available). And not fire more than necessary.

http://jsfiddle.net/katspaugh/xqeDj/


References:

textInput — a W3C DOM Level 3 event type. http://www.w3.org/TR/DOM-Level-3-Events/#events-textevents

A user agent must dispatch this event when one or more characters have been entered. These characters may originate from a variety of sources, e.g., characters resulting from a key being pressed or released on a keyboard device, from the processing of an input method editor, or resulting from a voice command. Where a “paste” operation generates a simple sequence of characters, i.e., a text passage without any structure or style information, this event type should be generated as well.

input — an HTML5 event type.

Fired at controls when the user changes the value

Firefox, Chrome, IE9 and other modern browsers support it.

This event occurs immediately after modification, unlike the onchange event, which occurs when the element loses focus.

9
votes

As an extention to katspaugh's answer, here's a way to do it for multiple elements using a css class.

   $('.myclass').each(function(){
        $(this).attr('oldval',$(this).val());
   });

   $('.myclass').on('change keypress paste focus textInput input',function(){
       var val = $(this).val();
       if(val != $(this).attr('oldval') ){
           $(this).attr('oldval',val); 
           checkLength($(this).val());
        }
    });
6
votes

It took me 30 minutes to find it, but this is working in June 2019.

<input type="text" id="myInput" oninput="myFunction()">

and if you want to add an event listener programmatically in js

inputElement.addEventListener("input", event => {})
3
votes

Do it the jQuery way:

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


$('#name').keyup(function() {
  alert('Content length has changed to: '+$(this).val().length);
});
0
votes

You can use onkeyup

<input id="name" onkeyup="checkLength(this.value)" />
0
votes

You would have to use a combination of onkeyup and onclick (or onmouseup) if you want to catch every possibility.

<input id="name" onkeyup="checkLength(this.value)" onmouseup="checkLength(this.value)" />
0
votes

Here is another solution I develop for the same problem. However I use many input boxes so I keep old value as an user-defined attribute of the elements itself: "data-value". Using jQuery it is so easy to manage.

        $(document).delegate('.filterBox', 'keyup', { self: this }, function (e) {
            var self = e.data.self;

            if (e.keyCode == 13) {
                e.preventDefault();
                $(this).attr('data-value', $(this).val());
                self.filterBy(this, true)
            }
            else if (e.keyCode == 27) {
                $(this).val('');
                $(this).attr('data-value', '');
                self.filterBy(this, true)
            }
            else {
                if ($(this).attr('data-value') != $(this).val()) {
                    $(this).attr('data-value', $(this).val());
                    self.filterBy(this);
                }
            }
        });

here is, I used 5-6 input boxes have class 'filterBox', I make filterBy method run only if data-value is different than its own value.