我一直试图通过'getElementById()'和'.value'来验证我的字段.但是,似乎getElementById.value无效或某些代码与函数重叠.
更新了Javascript函数:
function validate() {
    var Name = document.getElementById('Name').value;
    var Tel = document.getElementById('Tel').value;
    var FaxNo = document.getElementById('FaxNo').value;
    if (Name != "") //wanted to check for alphabets only.
    {
         alert("Correct");
         return true; //doesnt go to next.php
    }
    else 
    {
          alert("Don leave blank!")
          return false;
    }
    if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
    {
        alert("Correct");
        return true; //doesnt go to next.php
    }
    else 
    {
      alert("invalid");
      return false
    }
  return true; //doesn't go to next.php
}
我的表格:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
我已经将我的onclick函数定义为我的Javascript并尝试添加return false.但警报仍然无法出现.好心提醒.
您的标记无效:
<input name="Name" type="text" id="Name" " value=""/>
                                         ^-----------should be removed
因此更正将删除所有额外的"字符:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
为防止submition,当输入无效时,您可以尝试以下方法:
function validate() {
    var Name = document.getElementById('Name').value;
    var Tel = document.getElementById('Tel').value;
    var FaxNo = document.getElementById('FaxNo').value;
    if (Name != "") //wanted to check for alphabets only.
        alert("Correct")
    else {
        alert("Don leave blank!")
        return false;
    }
    if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
        alert("Correct")
    else {
        alert("invalid");
        return false;
    }
}
//Borrowed from jQuery lib
function isNumeric( obj ){
    return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>