Javascript在按钮上无法正常工作

时间:2016-07-27 21:24:02

标签: javascript html function

我使用bootstrap创建了一个网页。有2个文本框和一个要提交的按钮。我编写了JavaScript函数,以便在任何文本字段为空时发出警报。我很惊讶地看到它不起作用。我的JavaScript功能是:

function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
  return false;
}else if (a==null || a=="")
  {
  alert("Field 1 is required");
  return false;
  }else if (b==null || b=="")
  {
  alert("Field 2 is required");
  return false;
  }else if(a!="" && b!="")
  {
  alert("Submitted Successfully");
  return true;
  }
}

我的表单代码是:

<form role="form" method="post" name="Form" onsubmit="return validateForm()">   
    <div class="row 150%">
        <div class="6u 12u$(medium)">
            <input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
        </div>
        <div class="6u 12u$(medium)">
            <input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
        </div>
    </div><br /><br />
    <button id="submit" class="button" style="vertical-align:middle">
        <span>Submit </span>
    </button>
</form>

1 个答案:

答案 0 :(得分:0)

你是如何包含validateForm javascript的?

例如,以下内容适用于我:

<html>
<body>
<script>

function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
  return false;
}else if (a==null || a=="")
  {
  alert("Field 1 is required");
  return false;
  }else if (b==null || b=="")
  {
  alert("Field 2 is required");
  return false;
  }else if(a!="" && b!="")
  {
  alert("Submitted Successfully");
  return true;
  }
}
</script>
<form role="form" method="post" name="Form" onsubmit="return validateForm()">   
    <div class="row 150%">
    <div class="6u 12u$(medium)">
        <input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
    </div>
    <div class="6u 12u$(medium)">
        <input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
    </div>
    </div><br /><br />
    <button id="submit" class="button" style="vertical-align:middle">
    <span>Submit </span>
    </button>
</form>
</body>
</html>