簡體   English   中英

復選框驗證javascript

[英]check box validation javascript

我需要驗證表上至少一個復選框的選擇。 我沒有使用警報,因為我已經在CSS上創建了一個類,該類以紅色突出顯示了輸入,選擇和其他未填寫的元素。

這是我的JS:

var btnRegister= document.querySelector('#btnRegisterRegObr');

btnRegister.addEventListener('click', function () {

    var bError= false; 
    //I am initializing this boolean variable so that it also shows an error
    //message on the screen if the user has not selected any option at all...

    var elementCheckRegObr = document.querySelector('#checkRegObr');

    if (elementCheckRegObr.checked==false){

        bError=true;    
        elementCheckRegObr.classList.add('error'); 
        //This part of the code brings the error I have 
        //previously created on CSs if the checkbox is not checked

    }
    else{
        elementCheckRegObr.classList.remove('error');
    }
});

HTML上的按鈕在HTML上具有正確的ID:id =“ btnRegisterRegObr。

我在這里查看一些代碼,人們正在使用.checked == false進行驗證

但是,這似乎不適用於我的。

事實上,我首先想到我需要使用if(elementCheckRegObr.checked ==“”)的語法,但該語法似乎也不起作用。

我沒有驗證輸入,選擇或單選按鈕的問題,但是我不確定是否以正確的方式使用了復選框。 任何幫助或建議將不勝感激:)

我建議您使用getElementById來獲取元素,並測試是否以這種方式選中了該復選框:

if(document.getElementById('idOfTheCheckBox').checked){
 alert('hey, im checked!');
}

暫無
暫無

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

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