简体   繁体   中英

Add an onchange event listener to an html input field

I would like to add an onchange event to those input fields without 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 onchange event with javascript?

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

pure JS

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

// or

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

jQuery

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

Note

Note, that change event on the text field will be fired after the blur event. It's possible that your looking for keypress event's or something like that.

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

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onchange

or

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

https://developer.mozilla.org/en/docs/Web/API/EventTarget.addEventListener

use addEventListener in your window.onload

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

addEventListener

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM