检查字符串是否只包含数字,否则显示消息

Dar*_*ess 4 javascript validation

我有一个简单的表格,它在按下数字时执行计算,但是这应该只在输入数字时发生,如果添加了一个字母,我希望出现通知。有没有一个简单的功能来做到这一点?

形式

    <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>
Run Code Online (Sandbox Code Playgroud)

计算函数

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我目前正在查看 isNaN 函数,但不熟悉 JS 语法,因此不确定在哪里使用它。

Sud*_*oti 5

你的意思是:


//add inside your calc function
val1 = document.getElementById("value1").value;
if(/^\d+$/.test(val1)) {
 //proceed with rest of code
}
else {
 alert("Invalid");
 return false;
}

Run Code Online (Sandbox Code Playgroud)