0

我一直在研究这个 jQuery 表单,它只允许用户在填写所有字段后提交。所以基本上,提交字段(或者在我的情况下是“请求”字段)是灰色的,直到所有字段都不为空。但是我的按钮总是变暗,有人可以帮我解决这个问题吗?我有以下 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,任何帮助将不胜感激。

4

1 回答 1

1

我已经稍微调整了代码以使用过滤器函数来检索空文本框以及使用更改事件。

这是在 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();
    });
});
于 2013-03-12T00:10:46.427 回答