簡體   English   中英

使用JavaScript驗證復選框選中的屬性是否不為空

[英]Verify if checkbox checked property is not empty using JavaScript

我要驗證復選框的選中屬性。 如果未選中其中任何一個,則跨度顯示此句子:“您應該選擇其中一個”,而當我選擇其中一個時,該消息必須消失。

<form  method="get"action="#" onsubmit="return vali();">
    <span id="textspan" style="color:red"></span>
    <input type="checkbox" class='gender' id="male">male
    <input type="checkbox" class='gender' id="female">female
    <input type="submit" class="validate" value="send" />
</form>
function vali() {
    var bool = true;

    var checkedCount = $('input[class="gender"]:checked').length;
    if (checkedCount == 0) {
        $("#textspan").html('select one of them');
        bool = false;
    }
    if(checkedCount >= 1) 
    {
        $("#textspan").html('');
        bool = true;
    }

    return bool;    
}

您沒有為復選框的change(或click)事件添加任何功能:

您的函數“ vali()”已附加到表單提交中,這意味着您的函數僅在單擊“發送”按鈕后才能工作

因此,如果您遇到錯誤,並且不想在單擊其中一個(復選框)時遇到錯誤,則必須向該事件添加一個函數:

function vali() {
    var bool = true;

    var checkedCount = $('input[class="gender"]:checked').length;
    if (checkedCount == 0) {
        $("#textspan").html('select one of them');
         bool = false;
    }
    if(checkedCount >= 1) 
    {
        $("#textspan").html('');
        bool = true;
    }
    return bool;
}

$(".gender").click(function(){
    var checkedCount = $('input[class="gender"]:checked').length;
    if(checkedCount >= 1){
                $("#textspan").html('');
            }
});

由於只要您點擊“ .gender”之一,就會觸發您的點擊事件,因此最好具有以下功能:

$(".gender").click(function(){
    $("#textspan").html('');
});

嘗試下面

<form  method="get"action="#" onsubmit="return vali();">
    <span id="textspan" style="color:red"></span>

    <input type="radio" name="rad" class='gender' id="male">male
    <input type="radio" name="rad" class='gender' id="female">female
    <input type="submit" class="validate" value="send" />
    </form>

<script>        

        $(document).ready(function(){
        $(".gender").click(function(){
        $("#textspan").html('');
    });
    });

         function vali() {
            var bool = true;

                var checkedCount = $('input[class="gender"]:checked').length;
                if (checkedCount == 0) {
                    $("#textspan").html('select one of them');
                    bool = false;
                }
                if(checkedCount >= 1) 
                {
                    $("#textspan").html('');
                    bool = true;

                }
                return bool;

        }
        </script>

提琴手喜歡:- 這里

暫無
暫無

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

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