How does jQuery differentiate between function calls (e.g. on click) when using variable element IDs?

How does jQuery differentiate between function calls (e.g. on click) when using variable element IDs?

I have a number of files that are contained in a table, each row containing a checkbox and filename.

Each of these checkbox input elements has a uniquely generated ID which is “Item_” followed by a 5 unique digit number.

Ideally, I’d like to process the state of a checkbox when it the user selects it or deselects it. If I were to use the following to access when the user clicks on an item from the list, how would jQuery respond to the checkbox set/unset?

$("#Item_" + file_number).some_function_here();

Would jQuery keep track of the elements on the page which have the ID of Item_#### (e.g. Item_100, Item_1234, etc.)? These items would not be dynamic so the page will only contain elements that part of the page when it is loaded, so all the information jQuery needs for the processing is available when the page is first loaded. But I want to avoid generating a processing function for each element in the list to minimize the size of the page and keep the code clean so that the javascript/jquery would be the same across the pages, and only the file items would be changed.

Thank you for any help you can provide.

Answer

How does jQuery differentiate between function calls (e.g. on click) when using variable element IDs?

They’re stored in a closure inside jQuery’s internals. It’s not too dissimilar from the following:

const getElements = (selector) => {
  const elements = document.querySelectorAll(elements);
  return {
    someFn() {
      // do something with every element in `elements`
    }
  };
};

For what you’re doing, it sounds like you should give each item a class name instead of a separate ID, then add a change listener to all elements with that class. Then, the this inside the listener will refer to the element that was changed:

$('.item').on('change', function() {
  console.log(this); // refers to the input
  console.log('was just changed to', this.checked);
});

And then you can process the change appropriately, depending on the element and the checkbox state.

Leave a Reply

Your email address will not be published. Required fields are marked *