Elijah Yang
Elijah Yang

Reputation: 265

How to have multiple values to 1 select option?

I want my select option to change 2 things: an image and a price. However, since there can only be 1 option value, only one of the jQuery will work. How do I have more than 1 value in option? If it can't be done, what is a solution?

HTML:

<select id="panelfabric" onChange="swapImage()">
    <option value="$168">Normal</option>
</select>

jQuery:

// select panel image
$('#panelfabric').on('change', function() {
  $('#imageToSwap2').prop('src', 
    ['img/panel/', $('#panelfabric').val(), '.png'].join('')    
    );
});

// select panel price
$('#panelfabric').on('change', function () {
  $('#priceToSwap2').text($(this).val()
    );
});

P.S. I can't name the image $168.png so that will not be a solution.

Upvotes: 1

Views: 3163

Answers (2)

Barmar
Barmar

Reputation: 780723

I would go with Jon's data-XXX solution. Another option is to put a mapping table in your Javascript:

var item_data = {
    "whatever": { price: 168, image: "http://..." },
    "something": { price: 200, image: "http://..." },
    ... };

and then:

$("#panelfabric").on("change", function() {
    var item = $(this).val();
    $('#imageToSwap2').prop('src', item_data[item].image);
    $('#priceToSwap2').text('$'+item_data[item].price);
});

Upvotes: 1

Jon
Jon

Reputation: 437336

One solution would be to attach as many pieces of information as you need to the <option> using HTML5 data attributes:

<option value="whatever" data-price="$168" data-image="http://...">
    Normal
</option>

And then:

$('#panelfabric').on('change', function() {
  var $selected = $('#panelfabric').children(":selected");

  $('#imageToSwap2').prop('src', $selected.data("image"));
  $('#priceToSwap2').text($selected.data("price"));
});

Upvotes: 1

Related Questions