我有一个HTML表单。我被要求编写JS代码来验证表单中的数据并在同一页面上显示验证结果,而无需提交表单。我被告知要使用我的JS函数(在单击Submit时执行)返回false,以便不提交表单。我这样做但是当我运行我的页面时,表单验证的结果在页面上闪烁了半秒钟,并在表单提交时消失。我究竟做错了什么?这是我在JS中的内容:(第一个函数将一个事件监听器添加到我的表单的提交按钮)
function eventListener(){
var submitBtn = document.getElementById("sub");
submitBtn.addEventListener("click", validate, false);
}
function validate(){
var input1 = document.getElementById("book_1").value;
var input2 = document.getElementById("book_2").value;
var input3 = document.getElementById("book_3").value;
if(input1=="" || input2=="" || input3=="")
window.alert("Error: Please fill in all input fields");
else if(isNaN(input1) || isNaN(input2) || isNaN(input3))
window.alert("Error: Please enter numbers in the input fields");
else{
var total1 = input1*19.99;
var total2 = input2*86;
var total3 = input3*55;
var grandtotal = total1 + total2 + total3;
var container = document.getElementById("container");
var par = document.createElement("p");
container.appendChild(par);
par.innerHTML = "<h3>Basic XHTML (Quantity: " + input1 + "):</h3> $" + (total1)
+ "<br/> <h3>Intro to PHP (Quantity: " + input2 + "):</h3> $" + (total2)
+ "<br/> <h3>Advanced JQuery (Quantity: " + input3 + "):</h3> $" + (total3)
+ "<br/><br/> <h3>Final Total:</h3> $" + grandtotal;
}
return false;
}
window.onload = eventListener;
答案 0 :(得分:2)
将事件传递给validate函数并设置preventDefault,如下所示:
function validate(event){
event.preventDefault();
// your code here
}
如果需要,使用.submit()验证后提交表单;
答案 1 :(得分:0)
只需将监听器移动到表单:
<form id="f0">
<input value="foo" name="foo">
<button>Submit</button>
</form>
&#13;
// Place camera on x-axis
camera.position.set(10,0,0);
camera.up = new THREE.Vector3(0,0,1);
camera.lookAt(new THREE.Vector3(0,0,0));
&#13;
无论如何,监听器应该在表单上,因为它可以在不单击按钮的情况下提交。
表单似乎仍然在堆栈片段中提交,但是将其放在页面中并且代码可以正常工作。