Thomas Dittmar
Thomas Dittmar

Reputation: 1914

jQuery Image Picker - Select multiple images programmatically

I'm using the jQuery library Image Picker https://rvera.github.io/image-picker/

Let's pretend I have the same setup like that:

<select class="image-picker" multiple="multiple">
    <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
    <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
    <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
    <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
</select>

I can select a single image programmatically like that

$(".image-picker").val("1");
$(".image-picker").data('picker').sync_picker_with_select();

In this case the first image would be selected. What if I ant to select the image with value 1 and 4? I have tried that:

$(".image-picker").val(["1","4"]);
$(".image-picker").data('picker').sync_picker_with_select();

but this doesn't work.

Any help would be much appreciated.

Upvotes: 0

Views: 2708

Answers (2)

paulgv
paulgv

Reputation: 1828

It does work :

$(function() {
  $(".image-picker").imagepicker();
  $(".image-picker").val(["1", "4"]);
  $(".image-picker").data('picker').sync_picker_with_select();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/image-picker/0.3.0/image-picker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/image-picker/0.3.0/image-picker.min.css" rel="stylesheet"/>
<select class="image-picker" multiple="multiple">
  <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
  <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
  <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
  <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
</select>

Upvotes: 3

serraosays
serraosays

Reputation: 7859

You want to get all image objects in the select list. Since you're using a custom data- element, the jQuery selector is a bit wonky: select option[data-img-src]. Then figure out how many image objects you have (imgCount below) and run a for loop of corresponding length over that array:

// 1- Put all img assets into an array using jQuery toArray()
var imgArray = $("select option[data-img-src]").toArray();

// 2- Get number of image assets
var imgCount = imgArray.length;

// 3- Loop through array, limit to number of total objects in array
for (var i=0; i <= imgCount; i++) {

  //4- Do whatever you want with imgArray here

}

Upvotes: 0

Related Questions