如何在提交前获得表单的结果?我有
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div class="form">
<form name="form">
<input type="text" />
<br />
<input type="text" />
</form>
</div>
<p class="congrats"></p>
<input style="width:100px" value="check" id="a" type="button" />
<script>
//Get amount of empty inputs
$("#a").onload('click', function () {
var bad = 0;
$('.form :text').each(function () {
if ($.trim($(this).val()) == "")
bad++;
});
if (bad > 0)
$('.congrats').css("display", "block").text(bad + ' missing');
else
$('.congrats').hide();
//Get total inputs
console.log("Total inputs " + form.getElementsByTagName('input').length);
//Divide by complete inputs out of 100%
console.log("The percentage is " + 100 / form.getElementsByTagName('input').length + "%");
//Minus total inputs
console.log(form.getElementsByTagName('input').length - bad);
});
</script>
</body>
</html>
但是如何在实际点击之前获得结果,而不是页面加载? ONLOAD?
答案 0 :(得分:0)
您使用.onload
代替.on()
:http://jsfiddle.net/2Bt88/1/
您还需要阻止按钮的默认行为,然后继续:
$("#a").on("click", function(e) {
// Prevent default behaviour
e.preventDefault();
// Do stuff
// Submit the form
e.submit();
});
答案 1 :(得分:0)
将此添加到您的代码中
if (form.getElementsByTagName('input').length - bad === 0)
return false;
答案 2 :(得分:0)
根据您在更新的jsbin中提供的代码,您只需要明确调用countMissing()
函数:
countMissing();
//Get amount of empty inputs
function countMissing() {
var bad = 0;
$('.form :text').each(function () {
if ($.trim($(this).val()) == "") bad++;
});
if (bad > 0) $('.congrats').css("display", "block").text(bad + ' missing');
else $('.congrats').hide();
//Get total inputs
console.log("Total inputs "+form.getElementsByTagName('input').length);
//Divide by complete inputs out of 100%
console.log("The percentage is " + 100/form.getElementsByTagName('input').length+"%");
//Minus total inputs
console.log(form.getElementsByTagName('input').length - bad);
}