jQuery run same code for two different events
I have a form with a submit button.
I'd like to run the same 开发者_Go百科piece of code for when the user clicks submit or they hit Enter.
This is the code so far:
$('#submit').click(function(){
//code
return false;
});
but i'd like to run the same "code" when the user hits the enter key whilst focused on the input with id = "artistName"
var myfunction = function(){
//code
return false;
}
$('#submit').click(myfunction);
$('#artistName').keyup(function(event){
if(event.keyCode == 13){
myfunction();
}
});
put it into function
function function_name(){
//code
}
and trigger it like
$('#submit').click(function(){
function_name();
return false;
});
and trigger it whenever you want. for enter event, jut use .submit()
$("#form").submit(function(){
function_name();
return false;
});
You could try
$('#form_id').submit(function() {
//your code
}
This way your code will execute when the form is submitted either by submit button or by hitting enter
精彩评论