Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not execute jQuery stored inside array each time function is called

I currently store a few jQuery snippets inside an array which is stored inside a function. Once I call the function from my codebase, every jQuery snippet is executed. Hence, preventing me from working through the array.

The following code is an example:

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 assure that when deselect() is called, that only a few array elements get executed instead all of them?

Thanks!

like image 306
Chris Avatar asked Aug 25 '17 08:08

Chris


2 Answers

You are doing it wrong. The array elements execute when you declare it self.

Instead of everything 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"),
}

If you do not have any other select boxes apart from these, you could also simply do

$("select option").prop("selected", false);
like image 175
Suresh Atta Avatar answered Oct 03 '22 00:10

Suresh Atta


If you don't want them to be executed immediately, make it an array of functions, and call them in the loop with ().

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]();
}
like image 25
Barmar Avatar answered Oct 03 '22 00:10

Barmar