验证Javascript中的数字

时间:2014-07-20 20:42:19

标签: javascript

代码如下。我有一个用户输入半径,它显示一个圆的区域。我需要确保用户不输入负数或0半径。我应该添加什么来使这项工作?

<html>
  <head>
<title>Find the area and circumference of a circle</title>
 </head>
  <body>
 <script language="JavaScript">
  function CalculateArea(){
    var radius =document.form1.txtRadius.value;
    document.write("<P>The area of the circle is " + (radius * radius * Math.PI) + "                  </p>");

}
</script>
<form name=form1>
    Enter the radius of circle:
   <input type="text" name="txtRadius" size=10>
   <br>
   <input type="button" value="Calculate" onClick='CalculateArea();'>  
</form>
 </script>
 </body>
   </html>

3 个答案:

答案 0 :(得分:0)

有关document.write()功能的详情,请参阅

不要使用写入功能。优先使用document.createElement("p")创建新元素。

DEMO: http://jsbin.com/qabup/1/edit

function print() {
    var p = document.createElement("p"),
        text = Array.prototype.join.call(arguments, ", ");
    p.textContent = text;
    document.getElementById("console").appendChild(p);
    return text;
}

function CalculateArea() {
    var radius = parseInt(document.getElementById('txtRadius').value); // String to int.

    if (0 < radius)
        print("The area of the circle is " + (radius * radius * Math.PI));
    else
        print("Error message.");

    return false;
}

HTML:

<div>
    Enter the radius of circle:
    <input type="text" id="txtRadius" size="10" />
     <br>
    <input type="button" value="Calculate" onclick="CalculateArea()"/>
    <div id="console"></div>
</div>

旧解决方案:

试试这个:

var radius = parseInt(document.form1.txtRadius.value); // String to int.

if (0 < radius)
    document.write("<p>The area of the circle is " + (radius * radius * Math.PI) + "</p>")
else
    document.write("<p>Error message.</p>")

答案 1 :(得分:0)

试试这个:

input ID

提供给您
<input type="text" name="txtRadius" id="txtRadius" size="10" />

使用类似的方法检查值是否小于或等于0:

var num = document.getElementById('txtRadius').value;
var radius = parseInt(num);

if (radius > 0){
    alert('number is not less than 0');
else {
    alert('number is less than 0');
}

注意: document.write是一个坏习惯。相反,您可以使用someElement.innerHTML

有关这是一个坏习惯的更多信息,请参阅this

答案 2 :(得分:-1)

如果您希望使用JavaScript:

function isInteger(x) {
    return (Math.round(x) === x);
}

function CalculateArea(){
    var radius = document.form1.txtRadius.value;
    if(isInteger(radius) && radius > 0) {
        document.write("<P>The area of the circle is " + (radius * radius * Math.PI) + "
    } else {
        whatever you want to do if it's no integer or zero
        ...
    }
}