Refactor jquery to pass jquery-lint

320 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

The .toggle() method accepts a Boolean for showOrHide:

jQuery("input[name='newstate']").change(function(){
    // You can use this.checked instead of jQuery(this).attr("checked");
    jQuery('input[name="new-state-name"]').toggle(this.checked);
});

This way you'll know that the new-state-name input's display state always matches the newstate input (i.e., it will show when checked, unregarding it's previous state). What I mean is, using toggle() without showOrHide you can risk that the newstate state and new-state-name display state runs out of sync if e.g. the new-state-name input's display state is manipulated from outside the newstate change() handler.


Of course you could also just assign the result set to a temporary variable in order to perform the selector only once:

jQuery("input[name='newstate']").change(function(){
    var newStateInput = jQuery('input[name="new-state-name"]');
    if(this.checked) {
        newStateInput.show();
        // ... more here
    } else {
        newStateInput.hide();
        // ... and/or here
    }
});

if you intend to do more than show/hide.


EDIT
Oops, unfortunate typo. show() should be toggle() in first solution.

0
On
jQuery("input[name='newstate']").change(function(){
      jQuery('input[name="new-state-name"]').toggle();
});