user9767744
user9767744

Reputation:

Prevent a white space in the beginning of a input

Basically I been trying to design a js script that prevents a white space character from existing from the beginning of a input I been trying to figure this out but no luck so far. Most working examples of this subject is based in jQuery I can't find any working examples in pure java script. No jQuery pure Javascript code advice.

//??
<input id='noWhiteSpaceAtTheStart' type='text'>

Upvotes: 6

Views: 17345

Answers (4)

Aruna Prabhath
Aruna Prabhath

Reputation: 242

you can use the following js function

 <script> 
                    function NoSpaces() { 
                            if (event.keyCode == 32) { 
                                    event.returnValue = false; 
                                    return false; 
                            } 
                    } 
            </script> 

and call it on onkeypress event in the textbox

<asp:TextBox ID="yourtextbox" runat="server" onkeypress="return NoSpaces()"></asp:TextBox> 

Upvotes: 0

vicky patel
vicky patel

Reputation: 705

var inp =  document.querySelector('#noWhiteSpaceAtTheStart');
inp.addEventListener("keypress",function(e){
var key = e.keyCode;
if(key === 32){
e.preventDefault();
return false;
}
})
<input id='noWhiteSpaceAtTheStart' type='text'>

Upvotes: 3

Mamun
Mamun

Reputation: 68933

You can try the RegEx /^\s/ to match white space at the start of the string. Then simply set the input value to blank ('') if the condition is true:

function validate(input){
  if(/^\s/.test(input.value))
    input.value = '';
}
<input id='noWhiteSpaceAtTheStart' oninput="validate(this)" type='text'/>

Upvotes: 9

Fabio Lolli
Fabio Lolli

Reputation: 889

let yourInput = document.getElementById('noWhiteSpaceAtTheStart');
yourInput.addEventListener('input', () => {
    yourInput.value = yourInput.value ? yourInput.value.trimStart() : '' 
})
<input id='noWhiteSpaceAtTheStart' type='text'/>

This should do the trick:

on input event, if input.value is undefined (testing for falsy is enough) set an empty string, just to make sure we don't call methods on an undefined object...

Otherwise, return the same value after calling trimStart on it!

EDIT: First answer I was suggesting using the change event - but that triggers only for "submits": clicking outside, pressing tab, and so on... The input event instead triggers at every edit.

Upvotes: 3

Related Questions