Click to See Complete Forum and Search --> : Get the datafield of check boxes that checked in datagrid(with java script)?


ahmad_n80
July 21st, 2007, 02:06 AM
i have a datagrid that have some checkboxes.
i introduce the check boxes in datagrid like:
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server"></asp:CheckBox>
</ItemTemplate>
how can i get the datafield(like id) of check boxes that checked, from database(with java script)
thanks.

andreasblixt
July 21st, 2007, 03:30 AM
If you only have one checkbox per row, here's what you could do:
Find the DataGrid element, then loop through all of its checkboxes. If you find one that's checked, get the columns of its parent row so that you can get the values associated with the row (such as ID).

var dataGrid = document.getElementById('ClientIDOfDataGrid');
var inputs = dataGrid.getElementsByTagName("INPUT");
for (var v = 0; v < inputs.length; v++) {
if (inputs[v].checked) {
var columns = inputs[v].parentNode.parentNode.getElementsByTagName("TD");
var id = columns[0].childNodes[0].nodeValue;

alert("Row with ID " + id + " is checked!");
}
}

Note that you'll have to adjust the DOM methods based on what your HTML looks like (For example, if the column is in a <label> tag, you need another parentNode). If you want the JavaScript to be simpler, you can attach a value attribute to the checkboxes in the RowDataBound event. The value should be something unique, so the value of the DataKey of the row would be a good idea to use. Then you would only need this:

var dataGrid = document.getElementById('ClientIDOfDataGrid');
var inputs = dataGrid.getElementsByTagName("INPUT");
for (var v = 0; v < inputs.length; v++) {
if (inputs[v].checked) {
alert("Row with ID " + inputs[v].value + " is checked!");
}
}