javascript 将 onchange 事件侦听器添加到 html 输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24865177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:28:22  来源:igfitidea点击:

Add an onchange event listener to an html input field

javascript

提问by rubo77

I would like to add an onchangeevent to those input fields without jquery:

我想onchange向那些没有 jquery 的输入字段添加一个事件:

<input type="text" id="cbid.wizard.1._latitude">
<input type="text" id="cbid.wizard.1._longitude">

I can already call the object with

我已经可以用

<script type="text/javascript">
    alert(document.getElementById('cbid.wizard.1._latitude').id);
</script>

In the end, I want to add this behaviour, that if you enter a pair of coordinates into the first input, I will spread the pair over the two input fields?

最后,我想添加这种行为,如果您在第一个输入中输入一对坐标,我会将这对坐标分布在两个输入字段上?

How do I add an onchangeevent with javascript?

如何onchange使用 javascript添加事件?

回答by Michal Leszczyk

Ummm, attach an event handler for the 'change' event?

嗯,为“更改”事件附加一个事件处理程序?

pure JS

纯JS

document.getElementById('element_id').onchange = function() {
  // your logic
};

// or

document.getElementById('element_id').addEventListener(
  'change',
  callbackFunction,
  false
);

jQuery

jQuery

$('#element_id').change(function() {
  // your logic
});

Note

笔记

Note, that changeevent on the text field will be fired after the blurevent. It's possible that your looking for keypressevent's or something like that.

请注意,change文本字段上的事件将在blur事件发生后触发。您可能正在寻找keypress活动或类似的东西。

回答by idmean

document.getElementById('cbid.wizard.1._latitude').onchange = function(){
   //do something
}

GlobalEventHandlers.onchange docs

GlobalEventHandlers.onchange 文档

or

或者

document.getElementById('cbid.wizard.1._latitude').addEventListener("change", function(){
    //do something
});

EventTarget.addEventListener docs

EventTarget.addEventListener 文档

回答by Sajad Karuthedath

use addEventListenerin your window.onload

addEventListener在你的window.onload

    window.onload=function(){    
document.getElementById('cbid.wizard.1._latitude').addEventListener("change", function(){
            //do something
        });
    };

addEventListener

添加事件监听器

回答by Jayesh Goyani

Please try with the below code snippet.

请尝试使用以下代码片段。

<body>
    <input type="text" id="cbid.wizard.1._latitude">
    <input type="text" id="cbid.wizard.1._longitude">
    <script type="text/javascript">
        var txt1 = document.getElementById('cbid.wizard.1._latitude');
        txt1.addEventListener('change', function () { alert('a'); }, false);
    </script>
</body>