问题
I have a login form where the user must view some text before they login. It is in a hidden div that will display after fist click event of a call to action on the form. I have disabled the enter key, but I would like to allow the user to use it after the div with the text is displayed. This is what I have so far, but the result is a disabled enter key for the entire experience.
$(document).ready(function () {
$('#textbutton').click(function () {
$('#textbox').toggle();
$('.usernameDiv,.passwordDiv').hide();
$('#textbutton').hide();
$('#submitbtn').attr('target', '_parent');
});
$('#form').keypress(function (e) {
if(e.which == 13) {
e.preventDefault();
}
if($('#textbox').is(':visible')
&& ($('#form').val().length > 1)) {
return;
}
});
});
回答1:
This should work. Now instead of just checking for the enter key e.which == 13 we're also checking for whether the div is visible.
$(document).ready(function () {
$('#textbutton').click(function () {
$('#textbox').toggle();
$('.usernameDiv,.passwordDiv').hide();
$('#textbutton').hide();
$('#submitbtn').attr('target', '_parent');
});
$('#form').keypress(function (e) {
//If enter is pressed and the div is not visible then preventDefault
if (e.which == 13 && !$('#textbox').is(':visible')) {
e.preventDefault();
}
if ($('#textbox').is(':visible') && ($('#form').val().length > 1)) {
return;
}
});
});
回答2:
How about unbinding it after it's visible?
var waitForEnter = function (event) {
if (event.which == 13) {
event.preventDefault();
}
}
$('#form').bind('keypress', waitForEnter);
$('#form').keypress(function() {
if ($('#textbox').is(':visible') {
$('#form').unbind('keypress', waitForEnter);
}
});
回答3:
There is few other ways to send form. It's better to block submitting form at all.
$(function(){
$('#form').submit(function(){
if( ! $('#textbox').is(':visible') )
return false;
});
});
来源:https://stackoverflow.com/questions/9146936/allowing-keypress-13-on-login-form-after-specific-div-is-displayed-on-page