I’m used to programming in C# and I frequently bind to the TextChanged event, for example textBox.TextChanged. This would be triggered the moment the user or the program or anything else causes the contents of the text box to change.
I’m having a little problem with my HTML form. There are some AJAX things happening, and some javascript validation. These things need to happen when the user makes their changes, however the events are only firing on certain conditions.
For example, I have a drop down menu:
<select name="costCtr" id="costCentres" onchange="loadWorkers()">
<?php echo $costCentreOptions; ?>
</select>
The expected result is that when the cost centre selection changes, the workers will be populated. This is not the case. If the user tabs to the dropdown menu and uses the keyboard to select the option, nothing happens! The only way to fire the event is to select the option by mouse, or to select the option with the keyboard and then press enter.
Similarly, I have a text field for a date, and a button next to it which shows a groovy javascript-based date-time-picker. It goes a little like this:
<input type="text" name="date" id="date" onchange="validateForm()" />
If the user clicks the button to show the date-time-picker, selects a date, clicks ok, and the date-time-picker drops the date string into the input field, the onchange event isn’t fired. In fact, the onchange event is only fired if the use changes the text by hand and then focuses away from the input field!
How do other web developers handle these events? Which events should I be binding to? Should I bind to body.onkeypress and then write a mountain of code to determine what, if anything, has changed and act accordingly? Other ideas?
For
<select>elements, I always useonkeyupin conjunction withonchange, like:…which will properly capture changes made using the keyboard.
For text fields, you can again use
onkeyupif you want to validate the input as the user types, oronblurif you want to validate when the user tries to leave the field, like:…or:
For text fields that are being used with a scripted date-picker, the best way to capture the selection event will depend upon your date-picker script. You should check its documentation to see what it says about capturing onchange/onselection events from the picker.