1

嗨,我是 javascript 新手。

我正在尝试实现一些 javascript 表单验证我正在尝试使用此处使用的技术: http ://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validation ://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validation 来测试表单中的空字段并使用警报警告用户但这对我不起作用当我提交一个空表单时继续到 jsp 文件并且 javascript 没有捕获错误

这是表单所在的 index.html 文件

<html>
  <body>
    <head>
    <script>
        function validateForm()
        {
            var stoneField=document.forms["bmiForm"]["stone"].value;
            var poundsField=document.forms["bmiForm"]["pounds"].value;
            var kgsField=document.forms["bmiForm"]["kgs"].value;
            var feetField=document.forms["bmiForm"]["feet"].value;
            var inchesField=document.forms["bmiForm"]["inches"].value;

            if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
            {
              alert("Please enter a weight and height");
              return false;
            }
            else
            {

             return true;
            } 
        }
    </script>
</head>
<form name ="bmiForm" action="PrintBMI.jsp" onsubmit="return validateForm()" method=post  style="width:250px;">
    <fieldset>
    <legend>BMI Calculator</legend>
    <h3>Enter your weight</h3>
    Stone <input type = text name = "stone" size = 1 maxlength = 2>
    Pounds <input type = text name = "pounds" size = 1 maxlength = 2>
    <br>
    <strong>OR</strong>
    <br>
    KGs <input type = text name = "kgs" size = 1 maxlength = 3>

    <h3>Enter your height</h3>
    Feet <input type = text name = "feet" size = 1 maxlength = 1>
    Inches <input type = text name = "inches" size = 1 maxlength = 2>
    <br>
    <strong>OR</strong>
    <br>
    Metres <input type = text name = "metres" size = 1 maxlength = 4>
    <p><input type=submit value = "Get BMI">
    </fieldset>
</form>
</body>
</html>'

有没有人看到我做错了什么。谢谢你的时间。

4

3 回答 3

1

在此代码中替换=为:===

if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )

阅读比较运算符

于 2013-01-31T10:57:26.637 回答
0

USE == 用于比较值。

在您的代码中替换下面的代码块。

if ( stoneField == null || stoneField == "" && poundsField == null || poundsField == "" && kgsField == null || kgsField == "" && feetField == null || feetField == "" && inchesField == null || inchesField == "" )
于 2013-01-31T11:00:31.307 回答
0
if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
        {
          alert("Please enter a weight and height");
          return false;
        }

在 if 中使用 ===,而不是 =

于 2013-01-31T10:58:12.347 回答