2017-10-07 63 views
1

如何獲得複選框的狀態而無需調用函數。沒有onclick或onchange事件的複選框狀態

這是針對我的表單需要的特定複雜驗證。

我一直都想聽聽它的狀態。

我將需要的東西。

  • 其狀態時checked
  • 狀態時unchecked

我知道這工作

<input type="checkbox" onchange="showAddress3(this)" id="askAddress3">Call my friend to get the address 

    <script type="text/javascript"> 

     function showAddress3() { 
      if ($('#askAddress3').is(":checked")) { 
       alert("Checkbox is checked."); 
      } else if ($('#askAddress3').is(":not(:checked)")) { 
       alert("Checkbox is unchecked."); 
      } 
     } 

    </script> 

我要檢查它的狀態,而不要求它改變事件的功能,類似於

<input type="checkbox" id="askAddress3">Call my friend to get the address 

    <script type="text/javascript"> 

      if ($('#askAddress3').is(":checked")) { 
       alert("Checkbox is checked."); 
      } else if ($('#askAddress3').is(":not(:checked)")) { 
       alert("Checkbox is unchecked."); 
      } 


    </script> 

這隻在頁面加載時有效,在切換時不起作用。任何建議或解決方法都將非常有幫助。

+0

只需調用'$( '#askAddress3')是( 「:勾選」)。'當你需要知道的狀態......哦哦 – Andreas

+0

事件偵聽器正是針對這種情況,當你想繼續傾聽一個事件。沒有更好的解決方案。如果你不想在你的HTML中使用'onchange'屬性,你可以在javascript中添加事件監聽器,但結果將是相同的。 – Walk

+0

沒有功能就沒有辦法做到這一點。但是,舉個例子,當用戶點擊提交按鈕時,你可以得到這個值,它不會是「實時」的,但它會工作,因爲你將獲得輸入的最後一個值(通過輸入獲取它)。值) – pharesdiego

回答

1

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="checkbox" id="askAddress3">Call my friend to get the address 
 

 
<script type="text/javascript"> 
 
    $('#askAddress3').on('change', function() { 
 
    if ($('#askAddress3').is(":checked")) { 
 
     alert("Checkbox is checked."); 
 
    } else if ($('#askAddress3').is(":not(:checked)")) { 
 
     alert("Checkbox is unchecked."); 
 
    } 
 
    }); 
 
</script>

+0

這工作,謝謝隊友! –

+0

@FayazAralikatti這是我的榮幸:) – zynkn

1

我的事情下面是你在找什麼?

觸發輸入標籤中沒有硬編碼onchange=''的更改?

$("input[type='checkbox']").on("change", function() { 
 
    if ($('#askAddress3').is(":checked")) { 
 
     alert("Checkbox is checked."); 
 
    } else if ($('#askAddress3').is(":not(:checked)")) { 
 
     alert("Checkbox is unchecked."); 
 
    } 
 
}) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="checkbox" id="askAddress3">Call my friend to get the address

+0

不,這不起作用 –

+0

我不認爲有另一種方式來獲得切換複選框狀態 –