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-name
input's display state always matches thenewstate
input (i.e., it will show when checked, unregarding it's previous state). What I mean is, usingtoggle()
withoutshowOrHide
you can risk that thenewstate
state andnew-state-name
display state runs out of sync if e.g. thenew-state-name
input's display state is manipulated from outside thenewstate
change()
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.