I've used someone else's answer to get this.
Jquery:
$("input:checkbox:not(:checked)").each(function() {
var columnName = $(this).attr('name');
$('td:nth-child(' + columnName + '),th:nth-child(' + columnName + ')').hide();
});
$("input:checkbox").click(function() {
var columnName = $(this).attr('name');
$('td:nth-child(' + columnName + '),th:nth-child(' + columnName + ')').toggle();
});
HTML:
<input type="checkbox" name="1" checked="checked"/>
It works when I put values in the :nth-child(1) but not when I include the variable. Am I doing it wrong or am I using the wrong Jquery library.
Any help would be appreciated!
I'm guessing you have one or more <input type="checkbox" />
where the name
attribute is not a number, or is not present.
For example:
<input type="checkbox" name="string" />
When using your code, this outputs the error you described:
Uncaught Error: Syntax error, unrecognized expression: :nth-child
See fiddle
A workaround would be to check that columnName
is a valid number:
var columnName = $(this).prop('name') || '0';
if (columnName.match(/^[1-9]\d*$/)) {
// columnName must start with a number between 1 to 9
// and can be proceeded by zero or more numbers only
}
Also, it would be a better idea to assign a class
to the checkboxes which are used to show/hide
the corresponding td/th's
.
<input type="checkbox" class="showHide" name="1" />
That way, you're only selecting/looping over the elements you want, and not every checkbox on the page.
$('input.showHide').click(function() { ... });