使用 jquery/javascript 限制文本框中第一个位置的空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15435036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
restrict space at first position in textbox using jquery/javascript
提问by Milind Anantwar
I have a situation where I need to restrict users from entering space in beginning of a TextBox. I am able to restrict space entry in TextBox. But not having any clues about not allowing at first position.
我有一种情况,我需要限制用户在 TextBox 的开头输入空格。我可以限制在 TextBox 中输入空格。但没有任何关于不允许在第一个位置的线索。
I am looking for a solution using JavaScript or jQuery. Any help would be appreciated.
我正在寻找使用 JavaScript 或 jQuery 的解决方案。任何帮助,将不胜感激。
回答by VisioN
keypress
event solution:
keypress
事件解决方案:
$("input").on("keypress", function(e) {
if (e.which === 32 && !this.value.length)
e.preventDefault();
});
回答by Nirav Gandhi
I tried but after writing something and moving the cursor to the first letter it allows a space there. This solution never allows entering a space character in the beginning of the text box.
我试过了,但在写了一些东西并将光标移动到第一个字母后,它允许在那里有一个空格。此解决方案不允许在文本框的开头输入空格字符。
$("input").on("keypress", function(e) {
var startPos = e.currentTarget.selectionStart;
if (e.which === 32 && startPos==0)
e.preventDefault();
});
回答by Rubens Mariuzzo
If you are using jQuery you can just call the trim method.
如果您使用的是 jQuery,则只需调用 trim 方法即可。
$.trim(' Hello World!'); // -> 'Hello World'
Note, this will remove all white space characters from the start and the end of your string.
请注意,这将从字符串的开头和结尾删除所有空格字符。
Here is a demo using a button: http://jsfiddle.net/3Enr4/
这是使用按钮的演示:http: //jsfiddle.net/3Enr4/