空输入字段的JavaScript验证

问候,我有这个输入字段,  <input name="question"/>我想在单击提交按钮时调用IsEmpty函数。


我尝试了下面的代码,但是没有用。有什么建议吗?


<html>


<head>

  <title></title>

  <meta http-equiv="Content-Type" content="text/html; charset=unicode" />

  <meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />

</head>


<body>



  <script language="Javascript">

    function IsEmpty() {


      if (document.form.question.value == "") {

        alert("empty");

      }

      return;

    }

  </script>

  Question: <input name="question" /> <br/>


  <input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />


</body>


</html>


慕标琳琳
浏览 355回答 3
3回答

慕桂英4014372

<script type="text/javascript">&nbsp; function validateForm() {&nbsp; &nbsp; var a = document.forms["Form"]["answer_a"].value;&nbsp; &nbsp; var b = document.forms["Form"]["answer_b"].value;&nbsp; &nbsp; var c = document.forms["Form"]["answer_c"].value;&nbsp; &nbsp; var d = document.forms["Form"]["answer_d"].value;&nbsp; &nbsp; if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {&nbsp; &nbsp; &nbsp; alert("Please Fill All Required Field");&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; }</script><form method="post" name="Form" onsubmit="return validateForm()" action="">&nbsp; <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>&nbsp; <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>&nbsp; <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>&nbsp; <textarea cols="30" rows="2" name="answer_d" id="d"></textarea></form>

慕村9548890

您缺少必填<form>元素。您的代码应如下所示:function IsEmpty() {&nbsp; if (document.forms['frm'].question.value === "") {&nbsp; &nbsp; alert("empty");&nbsp; &nbsp; return false;&nbsp; }&nbsp; return true;}<form name="frm">&nbsp; Question: <input name="question" /> <br />&nbsp; <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" /></form>

蓝山帝景

输入字段可以包含空格,您要防止这种情况:function isEmpty(str){&nbsp; &nbsp; return !str.replace(/\s+/, '').length;}例:function isEmpty(str){&nbsp; &nbsp; return !str.replace(/\s+/, '').length;}document.getElementById("name").addEventListener("input", function() {&nbsp; if( isEmpty(this.value) ) {&nbsp; &nbsp; &nbsp;console.log( "NAME IS EMPTY!" )&nbsp; }});<input id="name" type="text">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript