19

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?

1
  • 1
    document.getElementById('cbid.wizard.1._latitude').addEventListener('change',function() { <stuff here> },false); should work. Commented Jul 21, 2014 at 12:35

4 Answers 4

25

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Basically he's asking for a solution without jquery
But its nivce to have the jQuery equivalent too
4
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

3 Comments

Don't I need the window.onload?
You should use window.onload.
addEventListener("change", function(){...}); seems to work for the last element in the document if used in the same page how can I solve this. I have three sets of forms on the same page but the change event only affects the one I put last.
3

use addEventListener in your window.onload

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

addEventListener

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.