nathan
nathan

Reputation: 1506

jQuery/CoffeeScript/Rails doesn't call change() on my input

I've got a form with a text field and I'm trying to perform an action whenever the user changes its text:

<%= form_for @item do |f| %>
  <%= f.text_field :title, id: "edit_item_title" %>
  <%= f.submit 'Save' %>
<% end %>

And in my coffeescript file:

$(document).ready ->
  $('#edit_item_title').change ->
    alert("Changed!")

For some reason, the change() event isn't fired. Just to show that everything else is working, here is some code that DOES work, using keypress instead of change:

$(document).ready ->
  $('#edit_item_title').keypress ->
    alert("Changed!")

I can't use keypress because it doesn't take into account when the delete key is pressed, and I can't use keyup because it fires whenever the arrow keys are pressed.

I'm quite new to this. Any workaround or idea why this would be happening? Thanks!

Upvotes: 2

Views: 1058

Answers (2)

PGill
PGill

Reputation: 3521

Change event fires on input fields when it loses focus, you should be using keyup and detect the keyCode and respond accordingly

$(document).ready ->
 skipKeys = [37, 38, 39, 40] # Arrow keys

 $('#edit_item_title').keyup (e)->
  if (skipKeys.indexOf(e.keyCode) == -1) # To skip keys
    alert('ok')

Upvotes: 0

mu is too short
mu is too short

Reputation: 434985

Change-events don't fire until the <input> loses focus. From the fine specification:

4.10.5.5 Common event behaviors

[...] The change event fires when the value is committed, if that makes sense for the control, or else when the control loses focus.

So just typing something in an <input type="text"> won't trigger any change-events.

If you need to react to what's being type as it is being typed, then you'll want to use keyup, keypress, or keydown combined with @value and the keyboard event. Which one you use depends on what you need to do.

Demo of the various events: http://jsfiddle.net/ambiguous/hrrur2LL/2/

Upvotes: 2

Related Questions