HTML5 type = button工作,type = submit not?

时间:2017-05-06 12:29:31

标签: javascript html5

我有一个表单,我想验证,然后如果有效,运行JavaScript函数。为此,我有:



function updateMap() {
  //dummy
}

<form>
  <div class="group">
    <input type="number" id="hour" min="0" max="23" required>
    <span class="highlight"></span>
    <span class="bar"></span>
    <label>Hour of the day (0-23)</label>
  </div>
  <div class="group">
    <select class="weekselection" id="weekday" required>
      <option value="" disabled selected>Choose the weekday</option>
			<option value="0">Monday</option>
			<option value="1">Tuesday</option>
			<option value="2">Wednesday</option>
			<option value="3">Thursday</option>
			<option value="4">Friday</option>
			<option value="5">Saturday</option>
			<option value="6">Sunday</option>
		</select>
  </div>
  <div class="group">
    <select class="methodelection" id="normalization" required>
			<option value="" disabled selected>Choose data handling</option>
			<option value="0">Normalized data</option>
			<option value="1">Unnormalized data</option>
			<option hidden value="2">Normalization not needed in baseline</option>
		</select>
  </div>

  <div class="group">
    <select class="methodelection" id="method" onchange="setNormSelection()">
			<option value="" disabled selected>Choose the method</option>
			<option value="0">Baseline (daily/hourly mean)</option>
			<option value="1">SGD Regressor</option>
			<option value="2">Decision Tree</option>
			<option value="3">Neural Network - Multi-Layer Perceptron</option>
		</select>
  </div>
  <button type=button onClick="updateMap()">Show prediction!</button>
</form>
&#13;
&#13;
&#13;

这是有效的,但是我想实际检查字段的有效性。如果在此代码中我发送到<button type=submit onSubmit="updateMap()">Show prediction!</button>,则验证工作正常,但如果填写了字段,则updateMap()函数无法调用,页面就会闪烁,就好像它将自己更新为默认值。我错过了什么?

3 个答案:

答案 0 :(得分:0)

&#13;
&#13;
    this->addWidget(rb);
    this->addWidget(label);
}
&#13;
var form = document.querySelector('#personal-form'),
    nameField = document.querySelector('#form-name'),
    ageField = document.querySelector('#form-age');

var Main = {
  onFormSubmit: function(e){
    if (Main.formIsValid()) {
      alert('Form is valid, but we will not send it');
      e.preventDefault(); // remove if you want to send the form instead
    } else {
      alert('Form is invalid');
      e.preventDefault();
    }
  },
  formIsValid: function() {
    return nameField.value.length > 0 && parseInt(ageField.value) > 13;
  }
};

form.addEventListener('submit', Main.onFormSubmit);
&#13;
* {
  box-sizing: border-box;
}

form > div {
  clear: both;
}

form label {
  float: left;
  width: 150px;
  padding: .2em .5em;
  text-align: right;
}

form .actions {
  margin-left: 150px;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<form>元素的工作方式是它们包含各种表单字段(文本框,checbox,单选按钮等)以及所有表单字段数据在某处提交的方式(通过提交按钮)。

点击提交按钮后,name元素中的所有value<form>数据表单字段元素(或通过form属性附加到该元素)发送到表单action属性中指定的位置,并根据表单的method属性中指定的值发送数据。这意味着在提交表单时,浏览器将重定向并从action中指定的位置加载响应。这是正常的,也是表单提交过程的一部分。当然,这确实意味着当前页面将卸载。这种卸载/装载过程已被称为“回发”。将更多现代方法发送到服务器(如AJAX)可避免回发,并允许在不卸载当前页面的情况下接收来自服务器的响应。

现在,要将条目验证到表单中,您需要为表单的submit事件设置事件处理程序 - 而不是提交按钮的click事件。这看起来有点反直觉,但是当你点击一个提交按钮时,会触发两个事件 - 点击按钮然后提交表单。

在连接到表单的提交事件的函数中,您可以根据所需的逻辑进行验证。只有当您确定表单数据存在无效时,才会取消提交事件,从而阻止数据进入任何位置并阻止回发。

最后,请勿使用内联HTML事件属性(onclickonsubmit等)。有关原因,请参阅 this 。相反,在专用的JavaScript区域中执行所有事件绑定,并使用现代和标准的.addEventListener()对象方法。

这是一个缩小的例子:

// Get references to the HTML elements you'll need access to:
var theForm = document.querySelector("form");
var txtUser = document.getElementById("txtUser");
var btnSubmit = document.getElementById("btnSubmit");

// Now, we'll define our validation function.
function validate(evt){
  
  // This will keep track of whether we determine there is an error or not
  var error = false;
  
  // Always call .trim() on user input. It strips off any leading or trailing
  // spaces in the input.
  if(txtUser.value.trim() === ""){
    // There is no data in the text box!
    error = true;
    alert("You didn't enter your name!");
  }
  
  // Other validations would go here and they would set error = true if
  // they fail.
  
  // After all the validations, we determine if the event should be cancelled
  if(error){
    evt.preventDefault();      // Cancel the form submission
    evt.stopPropagation();     // Cancel event propagation to other objects  
  } else {
    // This else section is normally not needed, but you said you wanted to
    // run another function if the form was valid, so this is the place to do that
    otherFunction();
  }
}

// Set up your submit event handler. We do this in JavaScript these days
// not in the HTML with onsubmit.
theForm.addEventListener("submit", validate);

function otherFunction(){
  alert("Other function when data is valid is running!");
}
<form action="#" method="post">

  <input type="text" name="txtUser" id="txtUser">
  <input type="submit" value="Submit" id="btnSubmit">

</form>

答案 2 :(得分:-1)

onsubmit一样使用按钮属性,而不是表单属性

<from onsubmit="return updateMap()"> 
  <button type="submit" >Show prediction!</button>
</form>

试试此代码

&#13;
&#13;
function updateMap(e) {
  e.preventDefault(); //the will prevent from page refresh if not 

  //apply you validation code


  return false; // the will prevent from page refresh .
}
&#13;
<form onsubmit="return updateMap(event)">
  <div class="group">
    <input type="number" id="hour" min="0" max="23" required>
    <span class="highlight"></span>
    <span class="bar"></span>
    <label>Hour of the day (0-23)</label>
  </div>
  <div class="group">
    <select class="weekselection" id="weekday" required>
      <option value="" disabled selected>Choose the weekday</option>
			<option value="0">Monday</option>
			<option value="1">Tuesday</option>
			<option value="2">Wednesday</option>
			<option value="3">Thursday</option>
			<option value="4">Friday</option>
			<option value="5">Saturday</option>
			<option value="6">Sunday</option>
		</select>
  </div>
  <div class="group">
    <select class="methodelection" id="normalization" required>
			<option value="" disabled selected>Choose data handling</option>
			<option value="0">Normalized data</option>
			<option value="1">Unnormalized data</option>
			<option hidden value="2">Normalization not needed in baseline</option>
		</select>
  </div>

  <div class="group">
    <select class="methodelection" id="method" onchange="setNormSelection()">
			<option value="" disabled selected>Choose the method</option>
			<option value="0">Baseline (daily/hourly mean)</option>
			<option value="1">SGD Regressor</option>
			<option value="2">Decision Tree</option>
			<option value="3">Neural Network - Multi-Layer Perceptron</option>
		</select>
  </div>
  <button type="submit">Show prediction!</button>
</form>
&#13;
&#13;
&#13;