Kai Brach
Kai Brach

Reputation: 9

Replace value in HTML based on option "label" attribute

I need to replace a value on the page based on what is selected in a dropdown. More specifically I need to fill in the "label" value. Here's the HTML:

<select class="item-number">
  <option>Please select</option>
  <option value="123" label="Description about 123">123</option>
  <option value="456" label="Description about 456">456</option>
</select>

<span class="item-name">Description shows up here</span>

Now, if someone selects, say, option 123, I would need the text in the span to be replaced with "Description about 123". Is there a way to achieve this? I'm a JS/Jquery newbie and completely out of my depth here. ;)

Upvotes: 0

Views: 1706

Answers (4)

Mr_Green
Mr_Green

Reputation: 41832

Straight from jQuery documentation

$("select").change(function () {
    var str = "";
    $(".item-number option:selected").each(function (i) {
        if ($(this).attr('label')) 
            str = $(this).attr('label');
        else 
            str = "Description shows up here ";
    });
    $(".item-name").text(str);
}).trigger('change');

Working Fiddle

Make some changes to the above one to make it work more better :)

UPDATE 1(on OP's request):

$('select').on('change',function(){
   label= $(this).find(':selected').val();
   $('.item-name').text(label);
});

Working Fiddle

UPDATE 2:

$("select").change(function () {
    var str = "";
    str = $(".item-number option:selected").val();
    if (str == "Please select") {
        $(".no-add").show();
        $(".add").hide();
    } else {
        $(".no-add").hide();
        $(".add").show();
    }
    $(".item-name").text(str);
}).trigger("change");

Working Fiddle

Upvotes: 0

Olrac
Olrac

Reputation: 1537

Try this

$(document).on('change','select.item-number', function() {
    $('.item-name').text($(this).find(':selected').attr('label'));
});

Demo

Upvotes: 1

Vond Ritz
Vond Ritz

Reputation: 2012

$('.item-number').change(function () {
    var lbl = $(this.options[this.selectedIndex]).attr('label');
    $('.item-name').html(lbl);
});

here's the FIDDLE

Upvotes: 1

Mr. B.
Mr. B.

Reputation: 8697

It's that simple:

$("select.item-number").on("change", function() {
    $(".item-name").text($(this).find(":selected").attr("label"));
});

Fiddle: http://jsfiddle.net/9YLZF/

Cheers!

Upvotes: 0

Related Questions