2015-10-19 122 views
2

如何在jQuery中單擊按鈕時檢查複選框的屬性ID。Jquery複選框checked按鈕點擊獲取attr id

我有複選框的屬性id和一個按鈕,當我檢查複選框2,然後單擊按鈕我應該得到屬性id 2等。

FIDDLE

HTML代碼

<div id="checkboxlist"> 
    <div><input type="checkbox" id="1" class="chk"> Value 1</div> 
    <div><input type="checkbox" id="2" class="chk"> Value 2</div> 
    <div><input type="checkbox" id="3" class="chk"> Value 3</div> 
    <div><input type="checkbox" id="4" class="chk"> Value 4</div> 
    <div><input type="checkbox" id="5" class="chk"> Value 5</div> 
    <div> 
     <input type="button" value="button" id="buttonClass"> 
    </div> 
</div> 
+0

http://jsfiddle.net/3u6e7qn7/ – Omidam81

回答

4

附上您的按鈕單擊處理程序,然後使用:checked片斷選擇選中的複選框。然後map返回id值的結果,最後調用toArray方法。這裏是工作代碼:

$("#buttonClass").on("click", function() { 
 
    var checkedIds = $(".chk:checked").map(function() { 
 
    return this.id; 
 
    }).toArray(); 
 
    alert(checkedIds.join(", ")); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="checkboxlist"> 
 
    <div> 
 
    <input type="checkbox" id="1" class="chk">Value 1</div> 
 
    <div> 
 
    <input type="checkbox" id="2" class="chk">Value 2</div> 
 
    <div> 
 
    <input type="checkbox" id="3" class="chk">Value 3</div> 
 
    <div> 
 
    <input type="checkbox" id="4" class="chk">Value 4</div> 
 
    <div> 
 
    <input type="checkbox" id="5" class="chk">Value 5</div> 
 
    <div> 
 
    <input type="button" value="Delete" id="buttonClass"> 
 
    </div> 
 
</div>

+0

謝謝lonica! – Sjay

+0

@Sjay不客氣!樂意效勞。不要忘記標記答案:) –

2

您可以使用map()遍歷並獲得ID,使用get()得到它作爲一個數組。

$('#buttonClass').click(function() { 
 
    var ids = $(':checkbox:checked').map(function() { 
 
    return this.id; 
 
    }).get(); 
 
    $('#res').text(JSON.stringify(ids,null,3)); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="checkboxlist"> 
 
    <div> 
 
    <input type="checkbox" id="1" class="chk">Value 1</div> 
 
    <div> 
 
    <input type="checkbox" id="2" class="chk">Value 2</div> 
 
    <div> 
 
    <input type="checkbox" id="3" class="chk">Value 3</div> 
 
    <div> 
 
    <input type="checkbox" id="4" class="chk">Value 4</div> 
 
    <div> 
 
    <input type="checkbox" id="5" class="chk">Value 5</div> 
 
    <div> 
 
    <input type="button" value="button" id="buttonClass"> 
 
    </div> 
 
</div> 
 

 
<pre id="res"></pre>

+0

謝謝你pranav! – Sjay

相關問題