简体   繁体   中英

How to target data attribute of a select option?

I'm trying to make an image change based on the dropdown/select option that a user chooses. However, I need to do this using a data attribute rather than the easier option value, since I need that to be used for something else. I can't seem to figure out what I'm doing wrong. The code I've attached doesn't target the data-image attribute. And ideas what I'm doing wrong?

Example Code:

<html>
<div>
    *Flavor 1:
</div>
<div>
    <select class="custom-cupcake-flavor" name="custom-cupcake-flavor">
        <option data-image="noimage.jpg" value="">-- Please Choose an Option --</option>
        <option data-image="Chocolate-Covered-Strawberry.jpg" value="Chocolate Swirl">Chocolate Swirl</option>
        <option data-image="strawberryLemonade.jpg" value="Extreme Lemon">Extreme Lemon</option>
        <option data-image="Cookie-Dough-Delight.jpg" value="Vanilla Blast">Vanilla Blast</option>
    </select>
</div>


<br>

<div class="col-md-6">
    <img id="uploadedImage" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=400%C3%97400&w=400&h=400">
    <br>

</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

<div style="clear:both;"></div>
<script type='text/javascript'>
    $(document).ready(function() {
        var flavor;
        var image_name;

        $(".custom-cupcake-flavor").on('change', function() {
            flavor = $(this).data("image");
            image_name = ("/images/" + flavor);

            $('#uploadedImage').fadeOut(200, function() {
                $('#uploadedImage').attr('src', image_name).bind('onreadystatechange load', function() {
                    if (this.complete) $(this).fadeIn(400);
                });
            });
        });

    });
    <!-- Hides Product Image when "No image" option is selected.-->
    $(document).ready(function() {
        $('.custom-cupcake-flavor').on('change', function() {
            if (this.val() !== "") {
                $("#uploadedImage").hide();
            } else {
                $("#uploadedImage").show();
            }
        });
    });
</script>

</html>

You can use the :selected selector to get the selected option in your dropdown:

$('.custom-cupcake-flavor').on('change', function() {
    var $option = $(this).find(':selected');
    var imageUrl = $option.data('image');

    // You might want to do something with imageUrl here:
    $('#uploadImage').attr('src', imageUrl);
});
// If you want to run the above on initial load you can trigger the change event:
// $('.custom-cupcake-flavor').trigger('change'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM