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'>
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'>
Share
Improve this question
edited Jun 7, 2018 at 10:10
asked Jun 7, 2018 at 10:05
user9767744user9767744
1
- 3 Are you referring to the small padding that comes before the input element or within the textbox ? because I dont see any white space within textbox – Ajanth Commented Jun 7, 2018 at 10:06
4 Answers
Reset to default 9You 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'/>
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.
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'>
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>