2013-03-18 46 views
1

我知道这个问题到处都是,但这让我疯狂!按键事件后无法清除文本框

这里是我的代码:

$(document).ready(function() { 

     $('#MainContent_LoginUser_Password').keypress(function (e) { 

      noCapsLock($('#MainContent_LoginUser_Password'), e, "Please turn off Caps Lock"); 
     }); 

    }); 
function noCapsLock(o, e, str) { 
var s = String.fromCharCode(e.which); 
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) { 
    alert(str); 
    o.val(''); 

}  
} 

我试图清除指定id文本框的值。上面的代码清除了文本,但是当按下新键时,显示该键的值(大写字母)。 我已经尝试了change(),keyup(),keydown()函数,但它们似乎仍然没有清除最后输入的值的文本框。

任何帮助将不胜感激。谢谢!

+0

我觉得你最好的拍摄将是一个计时器:( – Ven 2013-03-18 21:43:43

+0

我有点想通的问题在于当不同的函数被调用时(按键,keydown,keyup等)。但是,我需要寻找哪一个呢? – Jose 2013-03-18 21:45:00

回答

1

你只需要添加一个event.preventDefault();

您可能还希望把瓶盖内的功能,所以它不是全球性的,则不需要再次在方法内重新找到html元素:

$(document).ready(function() { 

    var noCapsLock = function(o, e, str) { 
     var s = String.fromCharCode(e.which); 
     if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) { 
      alert(str); 
      o.val(''); 
      e.preventDefault(); 
     }  
    }  

    $('#MainContent_LoginUser_Password').keypress(function (e) { 
     noCapsLock($(this), e, "Please turn off Caps Lock"); 
    }); 
}); 

踢我还做你的代码放到一个jQuery插件,你可以很容易地应用到任何元素(它不删除值只是停止按键):

(function($) { 
    $.fn.noCapsLock = function(message) { 
     this.keypress(function (e) { 
      var char = String.fromCharCode(e.which); 
      if (char.toUpperCase() === char && char.toLowerCase() !== char && !e.shiftKey) { 
       window.alert(message); 
       e.preventDefault(); 
      }   
     }); 
    }; 
})(jQuery); 

应用这样的:

$(document).ready(function() { 
    $('#MainContent_LoginUser_Password').noCapsLock('Please turn off Caps Lock!'); 
}); 
+0

那真是美丽!!!瞬间解决了!!!所以这可以防止事件发生,在这种情况下,按键?谢谢!只需要将“事件”改为“e”。 – Jose 2013-03-18 21:51:42

+0

@Jose很好的现场,我已经更新并添加了一些其他技巧哟你:-) – magritte 2013-03-18 22:00:12

+0

谢谢。我将这个标签作为答案,尽管对于我的目的@Vlad提供了一个有效的论点,并与他一起去,但这肯定是我发布的一般问题的解决方案!谢谢。 – Jose 2013-03-18 22:02:41

1

你必须取消与e.preventDefault();事件:

function noCapsLock(o, e, str) { 
    var s = String.fromCharCode(e.which); 
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) { 
     e.preventDefault(); 
     alert(str); 
     o.val(''); 
    }  
} 
1

我也不清楚你的情况的文本框;如果用户以小写字母输入长文本,然后点击CapsLock,然后继续输入 - 整个输入将被删除。

至于功能上,你可以调用事件的preventDefault()方法或返回false(你可以read here on the differences between the methods):

$(document).ready(function() { 

     $('#MainContent_LoginUser_Password').keypress(function (e) { 
      return noCapsLock(e, "Please turn off Caps Lock"); 
     }); 

    }); 
    function noCapsLock(e, str) { 
     var s = String.fromCharCode(e.which); 
     if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) { 
      alert(str); 
      return false; 
     } 
     return true; 
    } 
+0

您带来了一个非常有趣的观点。而你的解决方式似乎更加优雅。 – Jose 2013-03-18 21:54:29

+0

感谢人:)我标记了一个不同的帖子作为答案,但将与您一起去,因为你提出了一个非常有效的论点,这需要精心照顾这个问题! – Jose 2013-03-18 22:03:42