2

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.

3
  • 2
    Just run a trim method on it. Clean it up when the user stops typing and clean it up on the server. Commented Mar 15, 2013 at 14:35
  • With jQuery there's a method for trimming white spaces: $.trim('your.string') Commented Mar 15, 2013 at 14:36
  • can someone share any link or snippet for same. Commented Mar 15, 2013 at 14:37

3 Answers 3

15

keypress event solution:

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks vision.it almost does my job.just one more thing.can i also restrict space at the end of string??
@MilindAnantwar In this approach it is not effective, since you can't check which space is the very last while typing.
is there any other alternative that you can suggest?
This might also be a solution for me if prevent spaces for following conditions as well.1. Enter text e.g. san diago 2. remove "san" and "diago" only 3. Now " " is only remain there and it allows to add. Please help me to par from this situtaions
2

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

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.