我有一个我想验证的表单,然后如果有效,请运行一个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>
这有效,但是我想实际检查字段的有效性。如果在此代码中,我将其透露到<button type=submit onSubmit="updateMap()">Show prediction!</button>
,则该验证正常,但是如果填充字段,则updateMap()
函数未被调用,页面只是闪烁,就好像它已更新为默认值一样。我想念什么?
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);
* {
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;
}
<form id="personal-form">
<div>
<label for="form-name">Name</label>
<input name="name" id="form-name">
</div>
<div>
<label for="form-age">Age</label>
<input type="number" name="age" id="form-age" min="0" max="150">
</div>
<div class="actions">
<button type="submit">That's all!</button>
</div>
</form>
<form>
元素的工作方式是它们包含各种表单字段(文本框,checbox,无线电按钮等(,以及用于将表单数据提交在某个地方的所有表单数据的方式(通过提交按钮(。
单击"提交"按钮时,将name
和value
数据表单表单字段元素(或通过form
属性连接到其附加到其上的 CC_7属性(均发送到表单action
属性中指定的位置,并且数据是根据数据发送的至表单method
属性中指定的值。这意味着,当提交表单时,浏览器将重定向并从action
中指定的位置加载响应。这是正常的,并且是表格提交过程的一部分。当然,这确实意味着当前页面将卸载。这个卸载/加载过程已被称为"寄回"。更现代的方法将数据发送到服务器,例如Ajax,避免回发,并允许接收服务器的响应,而无需卸载当前页面。
现在,要将条目验证为表单,您需要为表格的submit
事件设置事件处理程序 - - 不是提交按钮的click
事件。一开始这似乎有点违反直觉,但是当您单击提交按钮时,两个事件开开 - 单击按钮,然后表单提交。
在连接到表单提交事件的功能中,您可以根据想要的任何逻辑进行验证。只有确定表单数据有无效的事情,您就可以取消提交事件,从而阻止数据进入任何地方并阻止寄回。
最后,不要使用内联HTML事件属性(onclick
,onsubmit
等(。有关原因,请参见此。而是在专用的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>
使用像这样的 onsubmit
不在按钮中属性属性
<from onsubmit="return updateMap()">
<button type="submit" >Show prediction!</button>
</form>
尝试此代码
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 .
}
<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>