问题
I am trying to update a div dynmically with a googlemap based on a zip code being entered. Its working fine if the user tabs away from the input box (id ZipCode) but if they press enter it doesn't blur the field. I have got a variation on this working with onkeyup, but one event calls the other and its a mess. Is it possible to kick the function off if either event occurs.
$(document).ready(function() { $("#ZipCode").blur(function() { $("#dynamic").load('googlemap.php', {zipcode: $('#ZipCode').val(), maxdistance: $("input[name='MaxDistance']:checked").val() }, function() { }); }); }) ;
Thanks for any pointers.
回答1:
You can do this:
$(document).ready(function() {
$("#ZipCode").bind('blur keyup',function(e) {
if (e.type === 'blur' || e.keyCode === 13)
// do your stuff here
});
});
Syntax: event.keyCode
Return Value: A Number, representing either a Unicode character code or the Unicode key code
回答2:
You could do this:
$(document).ready(function() {
$("#ZipCode").bind('blur keyup', function(e) {
if(e.type === 'keyup' && e.keyCode !== 10 && e.keyCode !== 13) return;
$("#dynamic").load('googlemap.php', {zipcode: $('#ZipCode').val(), maxdistance: $("input[name='MaxDistance']:checked").val() },
function() {
});
});
}) ;
回答3:
After re-reading your question, I think what you want to do is, when the textbox (i.e. #ZipCode
) is blurred, update the googlemap element; when enter key is pressed, blur the textbox, which in turn update the googlemap element.
In your comment you mentioned that, you don't want the Enter key to submit the form. You may need to handle the keypress
event as well.
$(document).ready(function() {
$("#ZipCode").blur(function() {
$("#dynamic").load('googlemap.php', {zipcode: $('#ZipCode').val(), maxdistance: $("input[name='MaxDistance']:checked").val() },
function() {
});
});
$("#ZipCode").keyup(function(e) {
if (e.which == 13) // Enter key
$(this).blur();
});
// prevent the Enter key from submitting the form
$('#ZipCode').keypress(function(e) { return e.which != 13; });
}) ;
回答4:
To allow only one event occurs. You can call the desired function in both the events blur
and keypress
. Finally the actual or desired function has to be called in blur event. Example<input disabled="true" type="text" placeholder="Enter Start Location" id = "fromPlaceEntry" onkeypress="startHandlingFromSubmission(event)" onblur="startHandlingFromSubmission(event)">
We can call the startHandlingFromSubmission()
function in the following way.
function startHandlingFromSubmission(e){
if(e.keyCode===13){ //To check enter event
$(e.target).blur();
}
if(e.keyCode===0){ //To check span event
setTimeout(function() {
handleFromPlaceSubmission(e);
}, 200);
}
}
function handleFromPlaceSubmission(e){
//This is the actual function which we desire to call
if(e.keyCode === 0){ //executing only in case of blur event
// your code goes here
}
}
来源:https://stackoverflow.com/questions/5432428/jquery-blur-and-the-enter-key