using jquery 1.6.1
When the check box gets checked or unchecked, i want to change the background color of the row. My closest tr is not getting selected here. I have a working code that i am changing to plugin and this problem only happens in the plugin.
Call:
$(".tableHighlightSelector tr td input[type='checkbox']").checkBoxTableHighlighter();
Plugin Code:
//checkbox row highlighter
jQuery.fn.checkBoxTableHighlighter = function(options){
var defaults = {
highlightClass: "rowhighlight"
};
var options = $.extend(defaults, options);
var highlight = {
RemoveHighlightForAllNotChecked: function ($item) {
$item.filter(':not(:checked)').closest("tr").removeClass(defaults.highlightClass);
},
CheckBoxRowSelect: function (e, $clicked) {
if ($clicked.attr("checked") == true) {
$clicked.closest("tr").addClass(defaults.highlightClass);
highlight.RemoveHighlightForAllNotChecked($('input[name=' + $clicked.attr("name") + ']')); //when we make checkbox behave like a radio button
}
else
$clicked.closest("tr").removeClass(defaults.highlightClass);
}
}
return this.each(function() {
var $obj = $(this);
var jsObj = this;
//onload
highlight.CheckBoxRowSelect('', $obj);
//click
$obj.click(function(){
highlight.CheckBoxRowSelect(e, $(this));
});
//keyup
$obj.keyup(function(){
highlight.CheckBoxRowSelect(e, $(this));
});
});
};
HTML:
<table width="300px" class="tableHighlightSelector">
<tr>
<td colspan="2">Group 2</td>
</tr>
<tr>
<td width="20px"><input type="checkbox" name="group2" value="a" checked="checked" /></td>
<td>A</td>
</tr>
<tr>
<td width="20px"><input type="checkbox" name="group2" value="b" /></td>
<td>B</td>
</tr>
<tr>
<td width="20px"><input type="checkbox" name="group2" value="c" /></td>
<td>C</td>
</tr>
<tr>
<td width="20px"><input type="checkbox" name="group2" value="d" /></td>
<td>D</td>
</tr>
</table>
I assume that you have defined the
.rowhighlightCSS class? I pasted this into jsFiddle and the highlighter worked straight away for<input checked="checked">!There were some missing event variables on the click handlers which the Chrome console was reporting immediately.
I assume this was a copy&paste error otherwise you can’t have been ever getting into the main
CheckBoxRowSelectfunction.The main problem overall is the checking if an input is checked logic which is incorrect. There are a few ways to check if an input is checked in jQuery and your test was not working. Replacing with
if ($clicked.is(':checked')) {as I have done in this demo fixes the logic and the row is highlighted.