How Do I Get An Input Alert Message To Work Only When Imputing Alphabets, Not For Numbers? Without Letting Any Text Tipped In
How do I get an input alert message to work only when imputing alphabets, not for numbers? Without letting any text tipped in. When imputing numbers there should be no alerts, but
Solution 1:
You need to use preventDefault()
if you want to to cancel the event, that is to disallow text box from accepting non-numeric input. So that you don't have to bother about deleting it. However, preventDefault()
does not work with onkeyup
. Use onkeydown
.
JS:
functioncheckKey(e)
{
if (e.keyCode != 8 && // allow backspace
e.keyCode != 46 && // allow delete
e.keyCode != 37 && // allow left arrow
e.keyCode != 39 && // allow right arrow
(e.keyCode < 48 || e.keyCode > 57)) // allow numerics only
{
e.preventDefault();
}
}
HTML:
<inputtype="text" onkeydown="checkKey(event)" />
Note - Alerting user on each key press / down / up is terrible. Simply annoying. Avoid! Silently block the unwanted keys as I showed above.
Solution 2:
Put a regular expression test in the onkeyup
attribute.
onkeyup="if(/\D/.test(this.value)) alert('no text here, input numbers only')"
Solution 3:
By playing around and mixing with different codes I found the answer on my own. I made a filter who lets only the characters chosen by me in the box and then added a alert message to it and WHALA there it works.
This is the answer I found:
JavaScript:
<scriptlanguage="javascript"type="text/javascript">functionTextFilter(myfield, e)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
elseif (e)
key = e.which;
elsereturntrue;
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
returntrue;
elseif ((("0123456789.").indexOf(keychar) > -1))
returntrue;
elseif ((keychar == ""))
{
if (myfield.value.indexOf(keychar) > -1)
returnfalse;
}
elsereturnfalse;
}
functioncheckInp()
{
var x = document.forms["isnform04"]["areinp"].value;
var regex = /^[0-9]+$/;
if (!x.match(regex))
{
alert("no text here, input numbers only");
returnfalse;
}
}
</script>
HTML:
<inputtype="text" name="areinp"id="test" size="30" value="" onChange="areCon()" onkeypress="return TextFilter(this, event)" onkeyup="checkInp()">
Post a Comment for "How Do I Get An Input Alert Message To Work Only When Imputing Alphabets, Not For Numbers? Without Letting Any Text Tipped In"