allowing keypress 13 on login form after specific div is displayed on page

元气小坏坏 提交于 2019-12-12 02:47:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!