在将文本粘贴到输入字段时如何防止空格? [英] How do you prevent spaces while pasting text into input field?
问题描述
如何防止空格粘贴到输入字段中?
How to prevent spaces from being pasted into an input field?
例如:我有两个不同的input
字段,分别用于名字和姓氏.不过,我已经通过使用简单的jQuery禁止将空格 typeing 输入到输入字段中,但是,似乎如果我将"Tom Riddle"复制并粘贴到任一输入字段中,则""Tom"和"Riddle"也将粘贴到输入字段中.
由于一个人的名字或一个人的名字将不包含任何空格,因此需要禁用.
这是jQuery
,用于禁止输入 的空格:-
For example: I have two different input
fields for first name and last name. I have disabled spaces from being typed into the input fields by using a simple jQuery, nevertheless, it seems that if I copied and pasted 'Tom Riddle' into either one of the input fields, the space between 'Tom' and 'Riddle' gets pasted into the input field as well.
edit: As a first name of a person or a last name of a person will not contain any spaces, I need to disable.
This is the jQuery
which I use for disabling spaces from being typed :-
$(document).ready(function() {
$('.no_space').keypress(function(e) {
if(e.which === 32) {
return false;
}
});
});
推荐答案
Bind the input event and replace the presence of spaces. For modern browsers, this covers both typing and pasting on an input field.
$('.no_space').on("input", function () {
$(this).val($(this).val().replace(/ /g, ""));
});
请参见演示.
这篇关于在将文本粘贴到输入字段时如何防止空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!