Reputation: 4312
I have a simple form, which performs a calculation when a digit is pressed, however this should only happen when numbers are typed, if a letter is added i would like for a notification to appear. Is there a simple function to do this?
Form
<input onKeyPress="return onlyNumbers()" onKeyUp="calc()" id="value1" type="text" name="value1">
<select onChange="calc()" id="manipulator" name="manipulator">
<option value="commission">Commission</option>
<option value="cost">Return</option>
</select>
</form>
calc function
function calc(){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
val1 = document.getElementById("value1").value;
mani = document.getElementById("manipulator").value;
if (val1 != ""){
document.getElementById("resp").innerHTML="Calculating...";
queryPath = "comCalcServ.php?value1="+val1+"&manipulator="+mani;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("resp").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",queryPath);
xmlhttp.send();
}
}
I am currently looking at the isNaN function but not familiar with the JS syntax so unsure where to use it.
Upvotes: 4
Views: 24007
Reputation: 4825
Try this simple one
if(val1.match(/^\d+$/)) {
// your code
}
Upvotes: 1
Reputation: 21
the above code did not work in my case . so i made few changes .
i just changed regex to /^[0-9]*$/.test(val1)
and it worked.
Upvotes: 0
Reputation: 100175
Do you mean:
//add inside your calc function
val1 = document.getElementById("value1").value;
if(/^\d+$/.test(val1)) {
//proceed with rest of code
}
else {
alert("Invalid");
return false;
}
Upvotes: 7