Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Event when input value is changed by JavaScript?

What is the event when an <input> element's value is changed via JavaScript code? For example:

$input.value = 12;

The input event is not helping here because it's not the user who is changing the value.

When testing on Chrome, the change event isn't fired. Maybe because the element didn't lose focus (it didn't gain focus, so it can't lose it)?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is no built-in event for that. You have at least four choices:

  1. Any time you change $input.value in code, call the code you want triggered by the change
  2. Poll for changes
  3. Give yourself a method you use to change the value, which will also do notifications
  4. (Variant of #3) Give yourself a property you use to change the value, which will also do notifications

Of those, you'll note that #1, #3, and #4 all require that you do something in your code differently from just $input.value = "new value"; Polling, option #2, is the only one that will work with code that just sets value directly.

Details:

  1. The simplest solution: Any time you change $input.value in code, call the code you want triggered by the change:

    $input.value = "new value";
    handleValueChange();
    
  2. Poll for changes:

    var last$inputValue = $input.value;
    setInterval(function() {
        var newValue = $input.value;
        if (last$inputValue != newValue) {
            last$inputValue = newValue;
            handleValueChange();
        }
    }, 50); // 20 times/second
    

    Polling has a bad reputation (for good reasons), because it's a constant CPU consumer. Modern browsers dial down timer events (or even bring them to a stop) when the tab doesn't have focus, which mitigates that a bit. 20 times/second isn't an issue on modern systems, even mobiles.

    But still, polling is an ugly last resort.

    Example:

    var $input = document.getElementById("$input");
    var last$inputValue = $input.value;
    setInterval(function() {
        var newValue = $input.value;
        if (last$inputValue != newValue) {
            last$inputValue = newValue;
            handleValueChange();
        }
    }, 50); // 20 times/second
    function handleValueChange() {
        console.log("$input's value changed: " + $input.value);
    }
    // Trigger a change
    setTimeout(function() {
        $input.value = "new value";
    }, 800);
    <input type="text" id="$input">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...