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 |3 Answers
Reset to default 15keypress
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/
$.trim('your.string')
– Rubens Mariuzzo Commented Mar 15, 2013 at 14:36