I have the following code in an html page
jQuery("input[name='newstate']").change(function(){
if(jQuery(this).attr("checked")) {
jQuery('input[name="new-state-name"]').show();
} else {
jQuery('input[name="new-state-name"]').hide();
}
});
But jquery lint gives following message.
You should only use the same selector more than once when you know the returned collection will be different. For example, if you've added more elements to the page that may comply with the selector
How do I modify my code to remove this message
The
.toggle()method accepts a Boolean forshowOrHide:This way you'll know that the
new-state-nameinput's display state always matches thenewstateinput (i.e., it will show when checked, unregarding it's previous state). What I mean is, usingtoggle()withoutshowOrHideyou can risk that thenewstatestate andnew-state-namedisplay state runs out of sync if e.g. thenew-state-nameinput's display state is manipulated from outside thenewstatechange()handler.Of course you could also just assign the result set to a temporary variable in order to perform the selector only once:
if you intend to do more than show/hide.
EDIT
Oops, unfortunate typo.
show()should betoggle()in first solution.