-1

I need help with strange behavior of my javascript/jQuery code.

jQuery .change() of simple text input executes only if i click on page or chrome console or press some key on keyboard, but not when i type text in my text input.

Sure, I expect, that code will be executed after each change in text input, but now this looks like:

  1. I type something in text input
  2. Nothing happens
  3. I click anywhere in the document or press a key, let's say, "tab"
  4. Code runs as expected

Can someone explain me whats going on?

Му code is simple:

$('#search_field').change(function() {
  alert("test")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_field" class="form-control" id="search_field" placeholder="Search" />
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
umaru
  • 178
  • 11
  • 1
    because that is what is should try on('input') – guradio Feb 08 '18 at 10:08
  • 2
    The `change` event fires on text inputs after the value of the element is amended *and* the element then loses focus. This is expected behaviour. If you want the event to fire when something is typed in the field, use `input`, `paste`, `keypress` or `keyup` – Rory McCrossan Feb 08 '18 at 10:09
  • 1
    Its the same question in stackoverflow https://stackoverflow.com/questions/1443292/how-do-i-implement-onchange-of-input-type-text-with-jquery – аlex Feb 08 '18 at 10:12
  • 2
    You could have simply read up on when the change event actually fires, for example here: https://developer.mozilla.org/en-US/docs/Web/Events/change#Description – CBroe Feb 08 '18 at 10:13

1 Answers1

3
  1. if you want to show on type use on('input')

$('#search_field').on('input',function() {
  alert($(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_field" class="form-control" id="search_field" placeholder="Search" />
guradio
  • 15,524
  • 4
  • 36
  • 57