簡體   English   中英

使用jQuery禁用表單提交按鈕input = text和input = checkbox

[英]Disable form submit button input=text and input=checkbox with jquery

我有一個帶有三個輸入的表單( [type=text] ,多個輸入[type=checkbox]和一個禁用的提交按鈕)。 如果用戶已填寫所有三個文本輸入至少選中了一個復選框,我希望啟用提交按鈕。

我發現這個小提琴在所有三個文本輸入上都很好用,但是我想添加一個附加條件,即必須至少選中一個復選框:

$(document).ready(function() {
    var $submit = $("input[type=submit]"),
    $inputs = $('input[type=text], input[type=password]');

    function checkEmpty() {
        // filter over the empty inputs
        return $inputs.filter(function() {
            return !$.trim(this.value);
        }).length === 0;
    }

    $inputs.on('blur', function() {
        $submit.prop("disabled", !checkEmpty());
    }).blur(); // trigger an initial blur
});

小提琴

在復選框中添加class="checkbox" ,然后將checkEmpty()修改為此:

function checkEmpty() {
    var text= $inputs.filter(function() {
        return !$.trim(this.value);
    }).length === 0;
    var checkbox = false;
    if ($(".checkbox:checked").length > 0) {
       checkbox = true;
    }
    if(text == true && checkbox == true){
        return true;
    }else{
        return false;
    }
}

然后單擊添加事件,復選框為:

$(".checkbox").on("click", function(){
    $submit.prop("disabled", !checkEmpty());
});

嘿,僅在jquery部分中添加輸入[type = checkbox],這是您所需的輸出,請嘗試以下代碼:Index.html

<form method="POST" action="">
    User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
    hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
    <input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script   src="https://code.jquery.com/jquery-1.12.4.js"   integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU="   crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
    var $submit = $("input[type=submit]"),
        $inputs = $('input[type=text], input[type=checkbox]');

    function checkEmpty() {
        return $inputs.filter(function() {
            return !$.trim(this.value);
        }).length === 0;
    }

    $inputs.on('blur', function() {
        $submit.prop("disabled", !checkEmpty());
    }).blur();
});
</script>

好吧,我現在有一個嚴重的問題。 我正在使用wordpress並添加:

<?php wp_head(); ?>
<?php wp_footer(); ?>

對於我的header.php和footer.php,因為我需要它們,所以插件正在加載。 自從我添加了它們以來,Stephan Sutter的工作解決方案不再起作用。 如果我填寫所有必填表格,則提交按鈕仍處於禁用狀態。 如果我刪除它們,它將再次起作用,但是我需要它們作為插件。

我認為這是因為插件將輸入文本添加到頁面中。 有什么方法可以將代碼frm Stephan用於已定義的表單ID =#addmovie-form?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM