我目前正在使用PHP设置一个页面,其上有三个数字输入字段。它看起来如下:
echo "Adult Tickets: <input type=\"number\" name=\"adulttickets[]\" value='0' id='adult' min='0' max='10'><br />";
echo "Child Tickets: <input type=\"number\" name=\"childtickets[]\" value='0' id='child' min='0' max='10'><br />";
echo "Student Tickets: <input type=\"number\" name=\"studenttickets[]\" id='student' value='0' min='0' max='10'><br />";
echo <<<_END
<input type="submit" onsubmit = 'return validate()' value="Submit booking details">
我想使用javascript来确保如果三种输入类型都没有从默认值零改变,则无法提交表单。为此,我设置了以下JS脚本:
<script>
function validate(){
var adult = document.getElementById('adult').value;
var child = document.getElementById('child').value;
var student = document.getElementById('student').value;
if(adult==0 && child ==0 && student==0){
alert("yes.");
return false;
}
return true;
}
</script>
然而,当我运行时没有任何事情发生。我是以正确的方式来做这件事的吗?有没有更好的方法来实现我刚才描述的结果?
答案 0 :(得分:2)
我想您下面有以下代码,只需将onsubmit
更改为onclick
<?php
echo "Adult Tickets: <input type=\"number\" name=\"adulttickets[]\" value='0' id='adult' min='0' max='10'><br />";
echo "Child Tickets: <input type=\"number\" name=\"childtickets[]\" value='0' id='child' min='0' max='10'><br />";
echo "Student Tickets: <input type=\"number\" name=\"studenttickets[]\" id='student' value='0' min='0' max='10'><br />";
?>
<input type="submit" onclick = 'return validate()' value="Submit booking details">
<script>
function validate(){
var adult = document.getElementById('adult').value;
var child = document.getElementById('child').value;
var student = document.getElementById('student').value;
if(adult==0 && child ==0 && student==0){
alert("yes.");
return false;
}
return true;
}
</script>
答案 1 :(得分:1)
你需要将输入值解析为数字(当前它们是字符串,即使输入类型是数字 - 值将是一个字符串),然后再进行比较;
var adult = parseInt(document.getElementById('adult').value);
var child = parseInt(document.getElementById('child').value);
var student = parseInt(document.getElementById('student').value);