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 for开发者_开发百科m should not be submitted.
any idea how to solve that?
http://jsfiddle.net/3UHVY/14/
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;
}
});
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.
}
});
JS Fiddle demo
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).
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:
- you can return false (to stop the event) after pressing up/down, to stop default up/down behavior (autocomplete suggestions)
- you can set changedByUpDown to false always when user inputs something different than up/down, so the form is "fresh"
- you can of course add code to submit the form when pressing enter (13)
精彩评论