Vertius
Vertius

Reputation: 23

Onchange image change javascript

It must be very simple, but can't find correct variant. I need to change image in select with onchange function but take instead of value attribute data-ima.

 <select onchange="changeSelection(this)" id="bundle-option-1550" name="bundle_option">
  <option value="5356" data-ima="pic.jpg">1</option>
  <option value="5357" data-ima="pic1.jpg">2</option>
  <option value="5358" data-ima="pic2.jpg">3</option>
  <option value="5359" data-ima="pic3.jpg">4</option>
</select>
 <img id="bundle"  src=""/>

and javascript which I use

function changeSelection(elem) {
var op = $(elem).find(':selected').data('ima')
var image = document.getElementById("bundle"),
image.src = elem.op;}

Upvotes: 1

Views: 155

Answers (4)

kamal pal
kamal pal

Reputation: 4207

jQuery("#bundle-option-1550").on('change', function(e){
    var op = $(this).find(':selected').attr('data-ima');
    document.getElementById("bundle").src = op;
});

Upvotes: 0

gemue
gemue

Reputation: 103

I think your code works if you change the last line of your javascript function from

image.src = elem.op;}

to

image.src = op;}

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15393

Use .attr() to set the src of the image

jQuery("#bundle-option-1550").on('change', function(e){
    var op = $(this).find('option:selected').data('ima');
    $("#bundle").attr('src', op);
});

Upvotes: 1

Hemal
Hemal

Reputation: 3760

Is this what you are looking for?

DEMO

CODE

$(document).ready(function(){

    $("#bundle-option-1550").change(function(){
        var dataimg = $(this).find("option:selected").attr("data-ima");

        $("#bundle").attr("src",dataimg);

    });
});

Upvotes: 2

Related Questions