如何检测表格中是否写入任何内容(使用javascript)?

时间:2012-03-02 04:19:25

标签: javascript forms

这是我的javascript代码:

if (username==null || isBlank(username))
  {
  document.getElementById("warning").innerHTML="Please Fill Out Username Box".fontcolor("red");
  return false;
  }
 if (email==null || isBlank(email))
  {
  document.getElementById("warning").innerHTML="Please Fill Out Email Box".fontcolor("red");
  return false;
  }
  if (password==null || isBlank(password))
  {
  document.getElementById("warning").innerHTML="Enter Password".fontcolor("red");
  return false;
  }

当我点击提交按钮时,根本没有点击表格,没有打印任何内容。有什么问题?

1 个答案:

答案 0 :(得分:0)

这可能是你想要的?

<form action="" name="someform">
    <input type="text" name="inputname" />
    <input type="submit" value="submit" />
</form>
<div id="warning"></div>
<script type="text/javascript">
function testForm ( e ) {
var inputname = this.inputname,
    warning = false;
    function isBlank ( elem ) {
        return elem.value === "";
    }
    // tests elems, you may put it into a loop
    if ( isBlank(inputname) ){
        warning = "<span style=\"color:red;\">some warning</span>";
    }
    // output
    if ( warning ){
        e.preventDefault();
        document.getElementById("warning").innerHTML=warning;
    }
}
// bind
document.someform.onsubmit = testForm;
</script>