为什么这个简单的JavaScript代码没有正常运行 http://codepen.io/anon/pen/wBXKQY HTML
<form id="scoreForm" name="scoreForm" onsubmit="validateForm();">
<label for="score">Score:</label>
<input id="score" name="score" />
<input type="submit" value="submit" />
</form>
js
function validateForm() {
var score = document.getElementById("score").value;
var scoreReg = /^\s*(\+|-)?\d+\s*$/;
if (score.match(scoreReg))
{ alert("the score pass"); return false; }
}
我只需要执行超出HTML5输入属性功能的验证。
答案 0 :(得分:1)
答案 1 :(得分:0)
<form id="scoreForm" name="scoreForm">
<label for="score">Score:</label>
<input id="score" name="score" />
<input type="submit" value="submit" />
</form>
<script>
document.getElementById('scoreForm').addEventListener('submit', validateForm);
function validateForm(ev) {
var scoreVal = +document.getElementById('score').value;
if (scoreVal < 10) {
alert('Sorry your score is too low!');
ev.preventDefault();
}
}
</script>
笔:http://codepen.io/ferahl/pen/GgGpLd
注意:
最好不要将ID用于任何事情,使用类,使用document.querySelector
或document.querySelectorAll
进行查询。
您看到的+
会转换为数字(它的简写)
更好地使用&#34;不引人注目的&#34; javascript - 我使用addEventListener
preventDefault
停止表单提交。还有另一个名为stopPropagation
的有用函数,您可以查看。返回false同时执行 - 最好知道您想要执行哪一项或两项。
答案 2 :(得分:0)
在这里调用validateForm()方法
<input type="submit" value="submit" onclick="validateForm();"/>
答案 3 :(得分:0)
代码笔中存在一些错误
你可以尝试w3schools http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit