Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an onchange event listener to an html input field

Tags:

javascript

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?

like image 377
rubo77 Avatar asked Jul 21 '14 12:07

rubo77


People also ask

How do I use Onchange input field?

Definition and UsageThe onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

What is Onchange in input?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.


2 Answers

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.

like image 53
Michal Leszczyk Avatar answered Sep 26 '22 00:09

Michal Leszczyk


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

GlobalEventHandlers.onchange docs

or

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

EventTarget.addEventListener docs

like image 22
idmean Avatar answered Sep 26 '22 00:09

idmean