Pure Javascript listen to input value change

后端 未结 6 954
不思量自难忘°
不思量自难忘° 2020-11-29 23:58

Is there any way I can create a constant function that listens to an input, so when that input value changes, something is triggered immediately?

I am looking for so

相关标签:
6条回答
  • 2020-11-30 00:35

    instead of id use title to identify your element and write the code as below.

    $(document).ready(()=>{
    
     $("input[title='MyObject']").change(()=>{
            console.log("Field has been changed...")
        })  
    });
    
    0 讨论(0)
  • 2020-11-30 00:36

    Default usage

    el.addEventListener('input', function () {
        fn();
    });
    

    But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.

    var event = new Event('input');
    el.addEventListener('input', function () { 
      fn();
    });
    form.addEventListener('input', function () { 
      anotherFn();
    });
    
    
    el.value = 'something';
    el.dispatchEvent(input);
    

    https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

    0 讨论(0)
  • 2020-11-30 00:52

    This is what events are for.

    HTMLInputElementObject.addEventListener('input', function (evt) {
        something(this.value);
    });
    
    0 讨论(0)
  • 2020-11-30 00:54

    Another approach in 2020 could be using document.querySelector():

    const myInput = document.querySelector('input[name="exampleInput"]');
    
    myInput.addEventListener("change", (e) => {
      // here we do something
    });
    
    0 讨论(0)
  • 2020-11-30 00:58

    Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

    HTMLInputElementObject.oninput = () => {
      console.log('run'); // Do something
    }
    

    Or can be written like below:

    HTMLInputElementObject.addEventListener('input', (evt) => {
      console.log('run'); // Do something
    });
    
    0 讨论(0)
  • 2020-11-30 01:00

    As a basic example...

    HTML:

    <input type="text" name="Thing" value="" />
    

    Script:

    /* event listener */
    document.getElementsByName("Thing")[0].addEventListener('change', doThing);
    
    /* function */
    function doThing(){
       alert('Horray! Someone wrote "' + this.value + '"!');
    }
    

    Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/

    0 讨论(0)
提交回复
热议问题