I’m working on a project and have a jQuery event handler I made to try to detect the presence of user entered data in a field as it’s being typed in. It kind of works with one weird side to it that has me a bit puzzled as to why this is happening.
The routine I wrote is this;
$(document).ready(function() {
$('#salary_bal').on('change blur keydown', function() {
if($(this).val.length === 0 || $(this).val() === '') {
setSubmitState('off');
} else {
setSubmitState('on');
}
});
});
function setSubmitState(state) {
switch(state) {
case 'on':
$('#fsSubmit').attr('disabled', false);
$('#fsSubmit').addClass('button');
$('#fsSubmit').addClass('cursor');
break;
case 'off':
$('#fsSubmit').attr('disabled', true);
$('#fsSubmit').removeClass('button');
$('#fsSubmit').removeClass('cursor');
break;
}
}
As you can probably guess by the setSubmitState calls, if the bound field does not have a value, it should disable the form’s submit button.
Like I said, this is “sorta” working right. The snag is that it’s actually acting like it’s responding to the previous character keyed in rather than an newly keyed in character.
Here’s the action sequences and their respective results;
- Enter a single ‘x’ into the field.
- Submit button does not become enabled.
- Enter another ‘x’ in the field.
- Submit button changes to enabled.
- Backspace and delete one ‘x’.
- Submit button remains enabled.
- Backspace again leaving field empty.
- Submit button remains enabled.
- Backspace one more time.
- Submit button changes to disabled.
I have been banging my head against a wall trying to debug this and am getting tired of spinning my wheels. (not to mention the headache from the wall) Can anyone offer a solution to this issue, please?
Keydown should be keyup, so event will fire after newly inserted character. Keydown fires before the keyup and a character enters into an input after keyup.