2017-04-18 62 views
0

我想,如果一個複選框被選中,以測試或根本沒有,我發現這個解決辦法,但我得到什麼如何知道一個複選框被選中

if(document.getElementById('checkbox-1').checked) { 
 
    alert("checked"); 
 
}
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox">

+2

重複http://stackoverflow.com/questions/2204250/check-if- checkbox-is-checked-with-jquery – ProgrammerV5

+2

[Check if checkbox is checked with jQuery]可能的重複(http://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery) – ProgrammerV5

+4

沒有真正的'事件'來觸發該JavaScript。也許這應該發生在複選框被選中或沒有?在'改變'也許? – sheriffderek

回答

1

你必須觸發點擊甚至複選框,將調用一個功能,執行所需的任務。

比如你可以怎麼做: -

function checkClick(){ 
 
    if(document.getElementById('checkbox-1').checked) { 
 
    alert("checked"); 
 
    } 
 
}
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox" onclick="checkClick()"> <!-- trigger click event using onclick and calling a function -->

注: - 你可以根據你的願望改變函數名。

+4

在現代,我們不應該鼓勵使用內聯事件處理程序。而且,這個問題是許多其他問題的重複。 –

+0

謝謝你爲我工作 – Amal

+0

@Amal樂於幫助你。 :) :) –

0

您需要觸發事件。對於複選框,只要值發生變化,onchange事件就會觸發。所以,你需要連接一個事件處理程序,它可以是一個函數引用或函數聲明類似onchange="checkboxChanged()

function checkboxChanged(){ 
 
if(document.getElementById('checkbox-1').checked) { 
 
\t \t alert('checked'); 
 
\t \t } 
 
    else{ 
 
     alert('Not checked'); 
 
    } 
 
}
<input id="checkbox-1" class="checkbox-custom" name="checkbox-1" type="checkbox" onchange="checkboxChanged()"/>

+0

謝謝你的工作 – Amal