1

I'm trying to fire a function whenever the value of an input field changes. The input field is in a lightbox so I have to delegate the event:

var validateDonation = function(elem) { var msg, value = elem.value; if (value == '') { msg = 'Please enter an amount'; } else if(parseInt(value, 10) < 1) { msg = 'Please enter an amount greater than 1'; } else if(parseInt(value, 10) > 100) { msg = 'Please enter an amount less than 100'; } else { msg = ''; } if(msg != '') { console.log(msg); } } 

and

$('body').delegate('#donation_amount', 'change', function(event) { validateDonation(this); }); 

If I use keyup instead of change the console log works just fine. But not on change. Why?

2
  • can you try $('body').on('change' , '#donation_amount', function(event) { validateDonation(this); }); Commented Jun 26, 2015 at 17:04
  • The change event doesn't even fire when the input is blurred and should fire the change event? or the event is firing upon change (blur of input) however you want the event to fire anytime the value of the input box changes instantly? Commented Jun 26, 2015 at 17:57

1 Answer 1

1

https://msdn.microsoft.com/en-us/library/ms536912(v=vs.85).aspx

onchange: This event is fired when the contents are committed and not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather when the user commits the change by leaving the text box that has focus. In addition, this event is executed before the code specified by onblur when the control is also losing the focus.

If you want the change to be instantly updated then you would want to use the oninput event

oninput: The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed. Additionally, it fires on contenteditable editors when its contents are changed.

For IE less than IE9 i believe you need to use the onpropertychange event as well as oninput to accommodate modern browsers.

Here is a fiddle to show you the event fires immediately

http://jsfiddle.net/SeanWessell/9jfkcapp/

Try this...

$('body').delegate('#donation_amount', 'input propertychange', function (event) { validateDonation(this); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.