4

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.

1
  • @DenysSéguret that won't work. Try parseFloat('12xxxx12') in your console and check what that returns :) Commented Sep 9, 2020 at 12:01

3 Answers 3

7

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;
}

Sign up to request clarification or add additional context in comments.

1 Comment

Stupid question but would this be inserted into the calc function? im unfamiliar with js.
1

Try this simple one

if(val1.match(/^\d+$/)) {
    // your code
} 

Comments

0

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.

2 Comments

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
not having enough reputation doen't mean i am wrong. i just wrote the lines which did my job

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.