如何在多个输入中禁止空格? [英] How to dis-allow spaces in multiple inputs?

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

问题描述

我有3个输入字段,我需要一个简短的jquery代码来禁止它们中的空格。

I have 3 input fields and I need a short jquery code to disallow spaces in them.

<input id='email' type='email' name='email' />
<input id='username' type='text' name='username' />
<input id='pwd' type='password' name='pwd' />


推荐答案

试试这个:

$('input').keypress(function (e) {

    // For detecting charCode, the following is the best cross-browser approach
    var charCode = e.which || e.keyCode;
    if (charCode === 32) {

        // the default action of the event will not be triggered.
        e.preventDefault();
    }
});

这将禁止所有输入中的空格。如果你只想在上面的三个或更多输入上禁用空格,只需在它们中添加一个类,如 myClass ,并调用如下函数:

This will disallow spaces in all the inputs. If you want to disallow spaces on only three of the inputs above or more, just add a class to all of them like myClass and call the function like:

$('.myClass').keypress(function (e) {

这篇关于如何在多个输入中禁止空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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