我一直在研究这个jQuery表单,它只允许用户在填写所有字段后提交。所以基本上,提交字段(或者在我的情况下是'request'字段)是灰色的,直到所有字段都没有空白。我的按钮总是变暗,有人会帮我这个吗?我有以下jQuery:
$(function() {
var $submit = $(".request input");
var $required = $(".required");
function containsBlanks(){
var blanks = $required.map(function(){ return $(this).val() == "";});
// the inArray helper method checks if value is within an array
return $.inArray(true, blanks) != -1;
}
function requiredFilledIn(){
if(containsBlanks())
$submit.attr("disabled","disabled");
else
$submit.removeAttr("disabled");
}
$("#form2 span").hide();
$("input").focus(function(){
$(this).next().fadeIn("slow");
}).blur(function(){
$(this).next().fadeOut("slow");
}).keyup(function(){
//Check all required fields.
requiredFilledIn();
});
requiredFilledIn();
});
这是我的表格
<div id="form2" title="Request a Call-back">
<p class="validateTips">All form fields are required. The submit button will activate once this is done.</p>
<form action="includes/requestcall.php" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" name="name" id="name" size="30" class="required" />
<span>Please enter your Name</span>
<br />
<br />
<label for="number">Number:</label>
<input type="text" name="number" id="number" size="30" class="required" />
<span>Please enter your number</span>
<br />
<br />
<label for="time">Preferred Time:</label>
<input type="text" name="time" id="time" size="30" class="required" />
<span>Please enter your preferred time</span>
<br />
</fieldset>
<p class="request">
<input type="submit" value="Request" class="btn-submit">
</p>
</form>
</div>
我还在学习jQuery,非常感谢任何帮助。
答案 0 :(得分:1)
我稍微调整了代码以使用过滤器功能来检索空文本框以及使用更改事件。
This is the link to the updated script running your markup on JSFiddle
这是更新的脚本:
$(function () {
var $submit = $("input.btn-submit").attr("disabled", "disabled").css("color", "red");
var $required = $(".required");
function requiredFilledIn() {
var blanks = $required.filter(function () {
return $(this).val() === "";
});
if (blanks.length > 0) $submit.attr("disabled", "disabled").css("color", "red");
else $submit.removeAttr("disabled").css("color", "black");
}
$("#form2 span").hide();
$("input:text").focus(function () {
$(this).next().fadeIn("slow");
}).blur(function () {
$(this).next().fadeOut("slow");
}).change(function () {
//Check all required fields.
requiredFilledIn();
});
});