Reputation: 44303
hey guys, i have a form that can be influenced with up and down keys.
without that code it's just a normal input-search field that fires a normal action. however i wonder how i can stop the default behaviour when i change the value of the input field with the Up and Down arrow keys.
check out this: http://jsfiddle.net/3UHVY/7
I only want the alert to happen if I change the value of the box with the up and down keys, otherwise no alert should be fired and the form should be submitted normally. However if the input-value is changed via the arrow keys JUST THE ALERT should be fired and the form should not be submitted.
any idea how to solve that?
Upvotes: 2
Views: 3433
Reputation: 23051
function FormHandler() {
var changedByUpDown = false;
this.onKeyDown = function(event) {
if (event.keyCode == 38 || event.keyCode == 40) {
changedByUpDown = true;
}
};
this.onSubmit = function(event) {
if (changedByUpDown) {
alert('Changed by up/down');
return false;
}
return true;
}
}
var fh = new FormHandler();
$('#search_form').submit(fh.onSubmit);
$('#searchsubmit').keydown(fh.onKeyDown);
Few notes:
Upvotes: 1
Reputation: 28147
var ok=0;
$(window).keydown(function(e) {
$('.s').focus();
switch ( e.keyCode ) {
case 38: // Up
$('.s').val('Up pressed');
ok=1;
break;
case 40: // Down
$('.s').val('Down pressed');
ok=1;
break;
case 13: // Enter
if(ok)
alert($('.s').val());
break;
default:
ok=0;
break;
}
});
Upvotes: 1
Reputation: 253328
I'm not entirely sure what you want to happen, but the following jQuery:
$('.s').keydown(
function(e) {
var keyPreesed = e.keyCode;
if (keyPreesed == 38) {
var msg = "Up was pressed.";
$(this).val(msg);
alert(msg);
}
else if (keyPreesed == 40) {
var msg = "Down was pressed.";
$(this).val(msg);
alert(msg);
}
else {
// meither 'up' nor 'down' was pressed, do whatever
// $(this).closest('form').submit(); // <- this (uncommented) will trigger the form's submission.
}
});
The problem is that I'm not sure where you want to trigger the submit, though I've assumed you want submission to occur if neither up nor down is pressed, hence it's in the else
statement).
Upvotes: 1