2017-08-04 105 views
0

我讀了很多關於這個問題的問題,但無論我做什麼,它都不起作用。檢查是否用動態ID檢查複選框

我有幾個複選框動態的ID,像:

More: 
<input type="checkbox" name="more" id="checkbox-more-285"> 
<br> Extra: 
<input type="checkbox" name="extra" id="checkbox-extra-285"> 

<button class="add_to_cart"> 
    Add to cart 
</button> 

285號可以是任何東西,我在其他地方使用。

然後,我有這樣的jQuery:

jQuery('.add_to_cart').click(function(e) { 
    e.preventDefault(); 

    if (jQuery("[id^='checkbox-more-']:checked")) { 
    console.log('1'); 
    } 

    if (jQuery("[id^='checkbox-extra-']:checked")) { 
    console.log('2'); 
    } 
    return false; 
}); 

正如你可以在的jsfiddle看到這裏https://jsfiddle.net/,每當我單擊添加到購物車按鈕,這兩個日誌都在控制檯上。

+1

嘗試'的jQuery(「[ID^=」複選框 - 更多 - ')「)。is(」:checked「)' –

回答

3

僅僅測試jQuery集合是不夠的,它總是真實的。在.length屬性添加到測試,像這樣:

if (jQuery("[id^='checkbox-more-']:checked").length) { // etc... 
0

您可以使用

jQuery("[id^='checkbox-more-']").is(":checked") 
{ 
    console.log('1'); 
    } 

if($("[id^='checkbox-more-']").prop('checked') == true){ 
    console.log('1'); 
} 
+0

'prop'在這裏可能不適合,因爲它只檢查第一個匹配,而不檢查可能有這樣一個'id'的其他元素。 – trincot