防止用jQuery在HTML文本框中输入空格 [英] Prevent typing spaces in an HTML text box with jQuery

查看:102
本文介绍了防止用jQuery在HTML文本框中输入空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到了一个 HTML 表单,用户可以输入它。我如何使用javascript / jQuery立即无缝删除文本框中的空格投放?我一直在研究 .val() jQuery方法,并提出了这个问题:

So I've got an HTML form that users can type in. How can I use javascript/jQuery to immediately and seamlessly remove spaces from a text box when one is put in? I've been researching the .val() jQuery method and came up with this:

$('input').keydown(function() {
    str = $(this).val();
    str = str.replace(/\s/g,'');
    $(this).val(str);
});

删除文本和空格的奇怪事情仍然显示在按键上,它们只是被删除以下按键。任何建议?

That does weird things to removing text and the spaces still show up on keystroke, they just get removed on the following keystroke. Any suggestions?

推荐答案

您可以通过检查按下的键是否是空格键并返回 false 如果是这样的话:

You could prevent it from being added at all by checking whether the key pressed is the space bar and returning false if so:

​$("input").on("keydown", function (e) {
    return e.which !== 32;
});​​​​​

以下是一个工作示例

这篇关于防止用jQuery在HTML文本框中输入空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆