I have a simple form which I would like to submit (i.e fire ajax) when the user presses enter (return) on an input field. If I press the submit button the event fires fine, but when using keyup to fire the exact same function the value of the input field is blank. I tried passing the value of the input field (from the keyup function) using $(this).val(), but the passed param was still blank.
Update II: The problem only occours on initial load. After hitting refresh the events fire as intended. Tested in Chrome and FF.
// Value of #pin is blank in getKeyAjax()
$('#pin').keyup(function(e) {
if (e.keyCode == 13) {
console.log('DEBUG: Keypress detected (13)')
getKeyAjax();
}
});
// Value of #pin is correct in getKeyAjax()
$('#btnPwdCreate').click(function() {
getKeyAjax();
});
function getKeyAjax() {
console.log('DEBUG: Starting ... getKeyAjax()');
var txtPin = $('#pin').val();
console.log('DEBUG: Value of txtPin: ' + txtPin);
.
.
.
}
I noticed on your fiddle one thing that might be causing this. In using the form field I noticed that sometimes I got an alert stating ‘4 digits only’ and usually I did not. The problem there is your
formtag. Hitting enter is triggering the browser’s default behavior: a non ajax form submit. If this goes through before your$.GEThas run, it would be consistent with the behavior you described, after refresh the js is cached and then might evaluate faster allowing the $.get just before the submit and refresh occurs. Its just a theory, but ultimately it leaves you with two options:<form>tag from your html.$('form').on('submit', function(e){e.preventDefault();});1# will have the effect of no default submits because there is no
<form>to do so. 2# overrides theonsubmitevent to prevent the default submit (letting you keep the form tag).Whether this solves the problem you are after or not, you do need it for your script regardless. Its going to be key to performing ajax while hitting enter on an input inside a form.
http://jsfiddle.net/9TYhT/
Fiddle above. Behavior is now consistent.