Jquery display multiple images in div from select/option field in form
I need some help finding a jQuery solution to display multiple images in a preview DIV from a select list of images in a form.
Example:
<select name="collection[]" id="collection" multiple="multiple">
<option value=""> - Select Image - </option>
<option value="image1.jpg">image1.jpg</option>
<option value="image2.jpg">image2.jpg&l开发者_运维问答t;/option>
<option value="image3.jpg">image3.jpg</option>
</select>
<div id="imagePreview">
Display image here, preferrably in a table/group. When the user deselects from the list the image disappears from this div.
</div>
I have seen this jquery script in an answer before (below), but it does not work with multiples.
<script type="text/javascript">
$(document).ready(function() {
$("#collection").change(function() {
var src = $(this).val();
$("#imagePreview").html(src ? "<img src='" + src + "'>" : "");
});
});
</script>
Any help greatly appreciated! Thanks.
If helpful to anyone, I built upon the solution and ended up with:
$("#collection").change(function () {
var str = "";
$("select option:selected").each(function () {
str += "<img src='" + $(this).val() + "' border='0' style='padding: 3px;' alt=\"" + $(this).text() + "\" /> ";
});
$("#imagePreview").html(str);
})
.change();
});
This gave me more control over the text and values in the form, and allows for more control over the img tag.
From the docs:
The .val() method is primarily used to get the values of form elements. In the case of
<select multiple="multiple">
elements, the .val() method returns an array containing each selected option.
So you just need to loop through each element in the src
array:
var src = $(this).val();
// Clear the preview area first
$('#imagePreview').empty();
// Loop through all selected options
for (var i = 0; i < src.length; i++) {
$("#imagePreview").append($('<img>', {src: src[i]}));
}
Note that I used $('<img>', {src: src[i]})
, which is an easier way of creating elements with dynamic attributes than joining strings together.
精彩评论