HTML JavaScript onChange Handler is not called when updated programatically

后端 未结 6 788
暗喜
暗喜 2021-01-19 04:28

I have found an odd anomaly with HTML text boxes and JavaScript that I have narrowed down to being a html/javascript peculiarity and I\'m hoping someone can educate me on.

6条回答
  •  余生分开走
    2021-01-19 05:01

    Your best bet is to put your code for handling the change in a function (say, handleTextChange), and then call that function both from the change event handler and when you make changes directly in your code.

    HTML:

     
    

    JavaScript:

    function changeField(id, value) {
        var field = document.getElementById(id);
        if (field) {
            field.value = value;
            handleFieldChange(field);
        }
    }
    

    Off-topic A couple of off-topic comments:

    • Probably best to use onchange, not onChange. In HTML, it doesn't matter; in XHTML, it matters, and the reflected property on the element is always all lower-case, so... And it's easier to type. :-)
    • Unless you have a good reason not to, I'd recommend hooking up event handlers after the fact rather than with inline HTML attributes. Because of browser differences, this is most easily done using a library jQuery, Closure, Prototype, YUI, or any of several others, but of course anything a library can do, you can do yourself, it just may take longer and receive less testing. :-)

提交回复
热议问题