Personally, I don't like the first two lines of code, but I'm aware that you're only concerned with this function and I wouldn't know how to improve those two lines without seeing the calling function. However:
Do the checkbox and rows share a common (and close) parent?
Example markup:
<tr>
<td>
<img src="../layouts/15/images/finished.png" />
</td>
<td>
<input type="checkbox" value="some value">
</td>
</tr>
In this case, the img
and input
share the same tr
. Meaning you could have this instead:
var $row = $('tr img[src="../_layouts/15/images/' + img + '.png"]').closest('tr');
var show = $('#' + checkBox, $row).prop('checked');
Specifically looking at this code: $('#' + checkBox, $row)
. Here we are looking for an element with the id
specified within the context of $row
. The advantage of this is that jQuery
doesn't traverse the whole DOM looking for that input, it only looks within the tr
. This won't make much of a difference in this case - but it's important to have this approach with performance in mind on client side. You may have also noticed that I renamed rows
to $row
? A lot of people will prefix a variable with a $
if the variable is a jQuery
selector, this gives other developers a bit more visibility.
Ternary operator
Instead of your if/else here you could use a ternary operator to reduce the lines of code:
show ? rows.show() : rows.hide();
Naming variables
The function variable names are a bit ambiguous in my opinion. To me checkBox
suggests I'm actually receiving a checkbox not the ID property. The same with img
applies here. More suitable ones might be:
function toggleRows(checkboxId, imgName)
.toggle()
. Instead ofif (show) ...
just userows.toggle(show);
\$\endgroup\$