Stephen Way
Stephen Way

Reputation: 678

Javascript/jQuery - Make array based on variable index of <option>

I would like to get the number of options in a select tag and then generate the same number of image paths from that.


$optionIndex = $("option", "select").index; // 2
imagePath = "/images/slider/slide-"
$images = "[" + imagePath + $optionIndex + ".jpg" + "]"; 

$(window).load(function() {
  var $slider = $(".slider").slider({
    images: $images // ideally this would show ["image1.jpg", "image2.jpg" etc…]
  });
}

Upvotes: 0

Views: 135

Answers (3)

StackSlave
StackSlave

Reputation: 10627

Try something like:

var selOps = $('#selectId>option'), imagePath = '/images/slider/slide-', imgs = [];
selOps.each(function(i){
  imgs[i] = imagePath+this.val()+'.jpg';
});
$(window).load(function(){
  var $slider = $(".slider").slider({
  // not sure there is an images property of the slider object, so I'm confused about this part
  });
});

Upvotes: 0

PSL
PSL

Reputation: 123739

One thing is $("option", "select").index should be $("option", "select").index(). Otherwise you will end up getting the function reference of index method. But i guess you wanted to take the length and then iterate.

But here you can just do:

 var $imagePathArray = $("select").find("option").map(function(i){ //<-- zero based index
        return  imagePath + i + ".jpg" ;
 }).get();

Demo

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You have to loop through and create an array like

$images = [];
for (var i=1;i<= $optionIndex ;i++)
{ 
   $images.push(imagePath + i + ".jpg");
}

Demo

Upvotes: 1

Related Questions