Do not execute jQuery stored inside the array every time a function is called

I currently store several jQuery fragments inside an array that is stored inside a function. As soon as I call a function from my code base, each jQuery fragment is executed. Therefore, it prevents me from working through an array.

The following is sample code:

var remove = [
    jQuery("#mesh option:selected").removeAttr("selected"),
    jQuery("#pipetype option:selected").removeAttr("selected"),
    jQuery("#caboption option:selected").removeAttr("selected"),
    jQuery("#bedsize option:selected").removeAttr("selected"),
    jQuery("#model option:selected").removeAttr("selected"),
    jQuery("#year option:selected").removeAttr("selected"),
];


for (var i = 0; i <= amount; i++) {
    remove[i];
}

How can I guarantee that when it is called deselect()that only a few elements of the array are executed, and not all?

Thanks!

+6
source share
2 answers

You are doing it wrong. Elements of an array are executed when you declare it yourself.

Instead of all you can just do

var remove = [ "mesh","pipetype", "caboption","bedsize", "model","year"];
for (var i = 0; i <= amount; i++) {
   jQuery("#"+remove[i]+" option:selected").removeAttr("selected"),
}

, ,

$("select option").prop("selected", false);
+5

, , ().

var remove = [
    () => jQuery("#mesh option:selected").removeAttr("selected"),
    () => jQuery("#pipetype option:selected").removeAttr("selected"),
    () => jQuery("#caboption option:selected").removeAttr("selected"),
    () => jQuery("#bedsize option:selected").removeAttr("selected"),
    () => jQuery("#model option:selected").removeAttr("selected"),
    () => jQuery("#year option:selected").removeAttr("selected"),
];


for (var i = 0; i <= amount; i++) {
    remove[i]();
}
+3

All Articles