Add an onchange event listener to an html input field

后端 未结 4 1392
孤城傲影
孤城傲影 2020-12-18 22:22

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




        
相关标签:
4条回答
  • 2020-12-18 22:46
    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

    0 讨论(0)
  • 2020-12-18 22:52

    use addEventListener in your window.onload

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

    addEventListener

    0 讨论(0)
  • 2020-12-18 22:59

    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.

    0 讨论(0)
  • 2020-12-18 23:02

    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>
    
    0 讨论(0)
提交回复
热议问题