Search code examples
javascriptjqueryonchangejquery-events

Change event not being triggered on text input


I'm trying to bind a function to 'change' event but it isn't working. So far I've tried using 4 methods.

1.

$('#search').on('change', function(){ console.log('a') })
$('#search').change(function(){ console.log('a') })
$(document).on('change', '#search', function(){ console.log('a') })
document.getElementById('search').onchange = function(){ console.log('a') }

None of them are working. I tried adding them from console (Chrome's dev tool).

Here is the page I am trying to make it work on. Any help will be appreciated. :)


Solution

  • Unlike the input event, the change event is not necessarily fired for each alteration to an element's value. You can/should use the input event instead of change. It fires on every keystroke and even if you just paste something from the clipboard:

    document.querySelector("#search").addEventListener('input', e => {
      console.log(e.target.value)
    })