簡體   English   中英

jQuery Validate不適用於自定義單選按鈕

[英]jQuery Validate does not work on custom radio buttons

我將jQuery Validate插件用於表單。 到目前為止,我尚未成功驗證我的自定義單選按鈕。 我已經閱讀了許多有關如何解決此問題的文章,例如,使用ignore ,但這並沒有幫助。

這是我的小代碼:

的HTML

<form id="my-form" name="my-form" method="post">
    <input type="text" name="myText">

    <p></p>

    <input type="radio" id="my-radio-1" name="myRadio">
    <label for="my-radio-1">selection #1</label>
    <input type="radio" id="my-radio-2" name="myRadio">
    <label for="my-radio-2">selection #2</label>

    <p></p>

    <p>
        <input type="submit" id="my-submit">
    </p>

</form>

JS

$('#my-form').validate({
    rules: {
        myText: {
            required: true
        },
        myRadio: {
            required: true
        }
    },
    errorClass: 'error_validate',
    errorPlacement: function (label, element) {
        label.insertAfter(element);
    }
});

帶有CSS的JSFIDDLE: https ://jsfiddle.net/d0nf4pqf/

有人知道如何啟用單選按鈕的驗證嗎?

問題很有趣。 您正在使用自定義樣式的單選按鈕,以及它如何工作,是CSS規則隱藏了本機input並改為顯示樣式的CSS單選。 結果,無線電輸入被隱藏了 ,但是jQuery驗證插件默認情況下會忽略隱藏的表單元素。

要修復它,您需要指示插件您也希望驗證隱藏字段。 為此使用ignore選項:

$('#my-form').validate({
    // specify rules
    ignore: [],
    rules: {
        myText: {
            required: true
        },
        myRadio: {
            required: true
        }
    },
    // change name of error class that is assigned to input fields
    errorClass: 'error_validate',
    errorPlacement: function (label, element) {
        // default
        if (element.is(':radio')) {
            label.insertAfter(element.next('label'));       
        }
        else {
            label.insertAfter(element);
        }
    }
});

另請注意,在這種情況下,您也需要修復errorPlacement函數。 您不能在輸入后立即附加錯誤元素,因為(由於自定義單選樣式,再次出現)然后單選/取消選中將不起作用(它使用相鄰的兄弟選擇器+ )。

演示: https : //jsfiddle.net/d0nf4pqf/1/

暫無
暫無

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

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