Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

jquery - Javascript change event on input element fires on only losing focus

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...