Reputation: 490
I am attempting to use jquery to detect checkbox changes in a specific table (i.e., "grid1").
(FWIW - the table is a jqgrid)
But, it appears that the "selector" statement I am using is not working the way I expect.
Instead of detecting checkbox changes within the specific table (i.e., "grid1"), it is also detecting/reacting to changes in the entire document - including "grid2".
I am clearly doing something wrong with my selector. --I just don't know what.
Thanks for any help on this :-)
FYI - The jquery "selector" code looks like this...
$("#grid1 :checkbox")
{
$(this).change( function(e)
{
var t = $(e.target);
var row = t.closest("tbody").children().index(t.closest("tr"));
var rowids = $('#grid1').jqGrid('getDataIDs');
var rowid = rowids[row-1];
var rowdata = $("#grid1").getRowData(rowid);
$("#grid1").jqGrid('setRowData', rowid, rowdata);
$("#grid1").setSelection(rowid);
});
};
...and the HTML structure that looks like this...
<body>
<form id="form1">
<div>
<div>
<input type="submit" id="submit" value="Submit Grid Edits" />
</div>
<div id="div1">
<table id="grid1"></table>
<div id="pager1" ></div>
</div>
<div id="div2">
<table id="grid2"></table>
<div id="pager2" ></div>
</div>
</div>
</form>
</body>
Upvotes: 0
Views: 148
Reputation: 9701
Why not do something like this:
$("#grid1 :checkbox").on("change", function(e) {
//do stuff
});
EDIT:
As both @sairn and @Oleg mentioned, this would be more appropriate:
$("#grid1").on("change", ":checkbox", function() {
//do stuff
});
Upvotes: 1
Reputation: 221997
I would recommend you to bind "change"
event on <table>
element instead of usage $("#grid1 :checkbox").on("change", ...);
. The main difference is that $("#grid1 :checkbox")
represent array of checkboxes. and binding will set separate event handles on every of the element. On the other side if you bind change
event of <table>
you set only one event handle. Because of event bubbling we can catch in the event handler "change"
event fired by child checkboxes. In the way you save a little memory needed to register every handle, but your code will be still very simple. See the old answer which discuss close problems.
The demo demonstrate the approach. The event handle looks so
$("#grid1").change(function (e) {
var $td = $(e.target).closest("td"), // the cell
$tr = $td.closest("tr.jqgrow"), // the row
rowid = $tr.attr("id"),
iCol = $.jgrid.getCellIndex($td[0]), // column index
colModel = $(this).jqGrid("getGridParam", "colModel");
// verify that event fired in the column "closed"
if (iCol >= 0 && colModel[iCol].name === "closed" &&
e.target.nodeName.toUpperCase() === "INPUT") {
alert("Chechbox in rowid=" + rowid + " clicked. It's " +
($(e.target).is(":checked") ? "checked" : "unchecked") + " now");
}
});
It displays results like the following
Upvotes: 1