Reputation: 67
I have a jquery function, that activates only when a table row is clicked and if so, it invokes controller method. However, this row also contains checkbox, and if i click it i don't want this method to be called. I tried checking the clicked element type or other parameters like class, but it seems to only apply to the entire row. Any ideas how to make it work?
JQuery:
function AllowTableRowsToBeClicked() {
$('#pref-table tbody tr').click(function () {
var resourceName = $(this).attr('title');
var categoryName = $('#pref-table').attr('name');
var url = "/Home/GetSpecific";
$.post(url, { categoryName: categoryName, resourceName: myClass }, function (data) {
});
});
}
cshtml:
<table class="table table-striped table-hover margin-top-20 pref-table" id="pref-table" [email protected]>
@for (int i = 0; i < Model.BiData.Count; i++)
{
<tr [email protected][i].Name name=@i title="@Model.BiData[i].Name" class="tableRow">
@Html.Hidden("resourceList[" + i + "]", Model.BiData[i].Name)
<th>
@Html.CheckBox("checkBoxList[" + i + "]", Model.BiData[i].Selected, new { @class = "resourceCheckbox" })
</th>
<th>
@Model.BiData[i].Name
</th>
</tr>
}
</table>
Upvotes: 1
Views: 702
Reputation: 1218
I think your problem is you don't want to activate your event code when user clicks on checkbox, irrespective of checkbox state.
$('#pref-table tbody tr').click(function (event) {
if($(event.target).is(":checkbox")) return;
// your event code
});
Upvotes: 0
Reputation: 2962
Using eventPropagation in the example below:
Html
<table width="100%">
<tr style="background:yellow">
<td>
<input type="checkbox" />
</td>
</tr>
</table>
javascript/jquery
$(document).ready(function() {
$('table tr').click(function(e) {
alert("row clicked");
});
$('input[type=checkbox]').click(function(e) {
e.stopPropagation();
alert("checkbox clicked")
});
});
Upvotes: 0
Reputation: 6608
If your checkbox has some id like box
then you can check if the event originated from that checkbox and stop processing.
$('#pref-table').on('click',function (event) {
if(event.target.id === 'box'){
return;
}
var resourceName = $(this).attr('title');
var categoryName = $('#pref-table').attr('name');
var url = "/Home/GetSpecific";
$.post(url, { categoryName: categoryName, resourceName: myClass }, function (data) {
});
Here's a Pen to demonstrate the idea.
Upvotes: 1
Reputation: 66490
$('#pref-table input[type="checkbox"]').click(function(e) {
e.stopPropagation();
});
Upvotes: 1