2

I want to fire input's on.input event if value is changed not by typing
Type something inside the input and then click the button

$('.inpsearch').on('input', function(){
    let a = $(this).val();
  console.log(a);
});

$('button').on('click', function(){
    $('.inpsearch').val('');
  // console.log expected here
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='search' class='inpsearch'>
<button>CLICK</button>
Paul T.
  • 4,703
  • 11
  • 25
  • 29
qadenza
  • 9,025
  • 18
  • 73
  • 126

2 Answers2

4

You could either trigger the input event as in my snippet or separate that functionality into a function and call it.

$('.inpsearch').on('input', function(){
    let a = $(this).val();
  console.log(a);
});

$('button').on('click', function(){
    $('.inpsearch').val('');
    $('.inpsearch').trigger('input');
  // console.log expected here
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='search' class='inpsearch'>
<button>CLICK</button>
painotpi
  • 6,894
  • 1
  • 37
  • 70
0

Unfortunately the input event is relatively new and only available to modern browsers (IE9+), verify compatibility

Here is the really good described answer about events.

My suggestion is to use keyup event instead of input event, Much like keydown, it triggers whenever the user releases a key, i have also implemented in your example:

$('.inpsearch').on('keyup', function(){
    let a = $(this).val();
    console.log(a);
});

$('button').on('click', function(){
    $('.inpsearch').val('');
    $('.inpsearch').trigger('keyup');
    // console.log expected here
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='search' class='inpsearch'>
<button>CLICK</button>

Note that keydown, keypress and keyup events carry with them information about the modifier keys Ctrl, Shift and Alt in the properties ctrlKey, shiftKey and altKey respectively and input event will not.

turivishal
  • 34,368
  • 7
  • 36
  • 59