DEV Community

Code And Deploy
Code And Deploy

Posted on

2 2

jQuery Single/Multiple Image Selector - Media Selector

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/jquery-plugins/jquery-singlemultiple-image-selector-media-selector

In this post, I will show you how to implement a Media Selector jQuery plugin which enables you to select single or multiple images (or any other elements) from a gallery.

jquery-singlemultiple-image

How to use the single/multiple image selector jquery plugin?

Step 1: Insert images

Insert images with check icons into labels of CSS class 'image-checkbox'. Remember to assign a unique ID to each image element utilizing the 'su-media-id' attribute.

<label class="image-checkbox">
    <img su-media-id="orange"
       src="img1.jpg" />
    <i class="fa fa-check"></i>
</label>
<label class="image-checkbox">
    <img su-media-id="apple"
       src="img2.jpg" />
    <i class="fa fa-check"></i>
</label>
<label class="image-checkbox">
   <img su-media-id="grapes"
        src="img3.jpg" />
    <i class="fa fa-check"></i>
</label>

Enter fullscreen mode Exit fullscreen mode

Step 2: Add Toggle Checkbox

Add a checkbox to toggle between Single Select and Multiple Select.

<input type="checkbox" class="custom-control-input" id="allowmultiple">
    <label class="custom-control-label" for="allowmultiple" style="cursor: pointer;">Select
    Multiple</label>
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Media Preview

Make an outcome container wherein the Media Selector shows a JSON string containing the image IDs you select.

<div id="selectedmediapreview"></div>
Enter fullscreen mode Exit fullscreen mode

Step 4: Load Styles

Load the CSS to style your image checkboxes.

.image-checkbox {
    cursor: pointer;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    border: 3px solid transparent;
    box-shadow: 0 0 4px #ccc;
    outline: 0;
    margin: 4px;
    border-radius: 12px;
}

.image-checkbox-checked {
    border-color: #2196f3;
}

img {
    border-radius: 8px;
    max-height: 160px !important;
    max-width: -webkit-fill-available;
}

.image-checkbox i {
    display: none;
    color: #2196f3;
}

.image-checkbox-checked {
    position: relative;
}

.image-checkbox-checked i {
    display: block;
    position: absolute;
    top: 10px;
    right: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Load the jQuery Library assets

 <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
    <script src="assets/js/scripts.js"></script>
Enter fullscreen mode Exit fullscreen mode

Step 6: Load the jQuery script

Initialize the JavaScript to activate the image selector.

jQuery(function ($) {
    var mediaArray = [];
    var selectedMediasId;
    var isMultipleAllowed = false;
    $('#allowmultiple').click(function () {
        isMultipleAllowed = $('#allowmultiple').is(':checked') ? true : false;
        $('.image-checkbox-checked').each(function () {
            $(this).removeClass('image-checkbox-checked');
        });
        mediaArray = [];
        $('#selectedmediapreview').html('');
    });


    $(".image-checkbox").on("click", function (e) {
        var selected = $(this).find('img').attr('su-media-id');
        //console.log(selected);
        if ($(this).hasClass('image-checkbox-checked')) {
            $(this).removeClass('image-checkbox-checked');
            // remove deselected item from array
            mediaArray = $.grep(mediaArray, function (value) {
                return value != selected;
            });
        }
        else {
            if (isMultipleAllowed == false) {
                $('.image-checkbox-checked').each(function () {
                    $(this).removeClass('image-checkbox-checked');
                });
                mediaArray = [];
                mediaArray.push(selected);
            } else {
                if (mediaArray.indexOf(selected) === -1) {
                    mediaArray.push(selected);
                }
            }
            $(this).addClass('image-checkbox-checked');
        }
        //console.log(selected);
        console.log(mediaArray);
        selectedMediasId = mediaArray.join(",");
        console.log(selectedMediasId);
        $('#selectedmediapreview').html('<div class="alert alert-success"><pre lang="js">' + JSON.stringify(mediaArray.join(", "), null, 4) + '</pre></div>');
        //console.log(isMultipleAllowed);
        e.preventDefault();
    });
});
Enter fullscreen mode Exit fullscreen mode

Step 7: Here is the full source

code of our Single/Multiple Image Selector

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Media Selector</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.6.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
    <link rel="stylesheet" href="assets/css/styles.css">
</head>

<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col mb-2">
                <div class="custom-control custom-checkbox mr-sm-2">
                    <input type="checkbox" class="custom-control-input" id="allowmultiple">
                    <label class="custom-control-label" for="allowmultiple" style="cursor: pointer;">Select
                        multiple</label>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <div class="mb-3 p-3" style="border-radius: 6px; border: 2px solid #cccccc42">
                    <label class="image-checkbox">
                        <img su-media-id="orange"
                            src="https://images.pexels.com/photos/161559/background-bitter-breakfast-bright-161559.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="kiwi"
                            src="https://images.pexels.com/photos/51312/kiwi-fruit-vitamins-healthy-eating-51312.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="strabery"
                            src="https://images.pexels.com/photos/934066/pexels-photo-934066.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="apple"
                            src="https://images.pexels.com/photos/533343/pexels-photo-533343.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="watermelon"
                            src="https://images.pexels.com/photos/1313267/pexels-photo-1313267.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="papaya"
                            src="https://images.pexels.com/photos/1824354/pexels-photo-1824354.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="lemon"
                            src="https://images.pexels.com/photos/952365/pexels-photo-952365.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="multifruit"
                            src="https://images.pexels.com/photos/142520/pexels-photo-142520.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="pumpking"
                            src="https://images.pexels.com/photos/673073/pexels-photo-673073.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>
                    <label class="image-checkbox">
                        <img su-media-id="tomatto"
                            src="https://images.pexels.com/photos/53588/tomatoes-vegetables-food-frisch-53588.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=100" />
                        <i class="fa fa-check"></i>
                    </label>

                </div>
            </div>
        </div>
        <div id="selectedmediapreview"></div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
    <script src="assets/js/scripts.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

This helpful jQuery plugin is developed by devsharif.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/jquery-plugins/jquery-singlemultiple-image-selector-media-selector if you want to download this code.

Happy coding :)

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay