javascript - 通过 getElementById() 验证

标签 javascript html

我一直在尝试使用带有“.value”的“getElementById()”来验证我的字段。但是,似乎 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>

我已经为我的 Javascript 定义了我的 onclick 函数,并且也尝试添加 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=""/>

为了防止提交,当输入无效时,你可以尝试这样的事情:

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()"/>

关于javascript - 通过 getElementById() 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11527569/

相关文章:

javascript - jquery将选定的属性分配给具有空格或特殊字符值的选择元素

javascript - 找出所有 9 人组成的组

javascript - 单击时隐藏 div - 多个框

javascript - D3 条形图故障排除

javascript - jQuery 中没有触发按钮单击事件?

javascript - JSON.stringify 和 JSON.parse 在 IE9 中不起作用?

javascript - jQuery:以最佳方式根据 URL 添加类

javascript - 编辑、保存、添加功能到动态表

javascript - 使复选框像单选按钮一样可以取消选中

javascript - 从node.js googledrive api返回结果