最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

restrict space at first position in textbox using jqueryjavascript - Stack Overflow

programmeradmin6浏览0评论

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.

I am looking for a solution using JavaScript or jQuery. Any help would be appreciated.

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.

I am looking for a solution using JavaScript or jQuery. Any help would be appreciated.

Share Improve this question edited Mar 15, 2013 at 14:39 Rubens Mariuzzo 29.2k27 gold badges122 silver badges149 bronze badges asked Mar 15, 2013 at 14:33 Milind AnantwarMilind Anantwar 82.2k25 gold badges96 silver badges127 bronze badges 3
  • 2 Just run a trim method on it. Clean it up when the user stops typing and clean it up on the server. – epascarello Commented Mar 15, 2013 at 14:35
  • With jQuery there's a method for trimming white spaces: $.trim('your.string') – Rubens Mariuzzo Commented Mar 15, 2013 at 14:36
  • can someone share any link or snippet for same. – Milind Anantwar Commented Mar 15, 2013 at 14:37
Add a comment  | 

3 Answers 3

Reset to default 15

keypress event solution:

$("input").on("keypress", function(e) {
    if (e.which === 32 && !this.value.length)
        e.preventDefault();
});

DEMO: http://jsfiddle.net/pdzBy/

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();
});

If you are using jQuery you can just call the trim method.

$.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/

发布评论

评论列表(0)

  1. 暂无评论