MANnDAaR
MANnDAaR

Reputation: 2590

Calling var array=[] within each function

I'm working on a project where I have different sets of div like heading, text, image etc..

Upon clicking I want to append input boxes for that relevant numbers of divs.

You can see working fiddle here : http://jsfiddle.net/UN62E/

This script does a job for me but I need improvement with this script.

This is how part of my script look like :

var eltofind = "heading";

if($(this).find("." + eltofind).length != 0){

    var eltoget = $(this).find("." + eltofind);

    $(eltoget).each( function(index) {
         var item = $('input.' + eltofind + ':first').clone();
        var count = (index +1);
        var getting = eltofind + "-" + count;
        item.addClass(getting);
        item.appendTo('#input');
    });
}

Currently I'm repeating whole script for individual sets of div. Is there a way to call all sets of divs within array? for example :

var eltofind = ["heading", "text", "image"] 

& call them within each function ?

My jQuery skills aren't that good & Any help would be appreciated.

Upvotes: 0

Views: 234

Answers (3)

mVChr
mVChr

Reputation: 50177

Just run $.each() on the array an replace eltofind with the el argument:

var elstofind = ["heading", "text", "image"];

$.each(elstofind, function(i, el){

    if($(this).find("." + el).length != 0){
        var eltoget = $(this).find("." + el);

        $(eltoget).each(function(index) {
            var item = $('input.' + el + ':first').clone();
            var count = (index + 1);
            var getting = el + "-" + count;
            item.addClass(getting);
            item.appendTo('#input');
        });
    }

});

Upvotes: 1

Ortiga
Ortiga

Reputation: 8814

You can make multiple selectors in jQuery

$(".heading, .text, .image").foo();

Upvotes: 3

Robert
Robert

Reputation: 8767

Create a loop that loops through each value of eltofind and performs the appropriate actions.

var eltofind = ["heading", "text", "image"];

for(var i=0; i < eltofind.length; i++){
     var thisElement = eltofind[i];

    if($(this).find("." + thisElement).length != 0){

        var eltoget = $(this).find("." + thisElement);

        $(eltoget).each( function(index) {
            var item = $('input.' + thisElement + ':first').clone();
            var count = (index +1);
            var getting = thisElement + "-" + count;
            item.addClass(getting);
            item.appendTo('#input');
        });
    }
}

Upvotes: 0

Related Questions