简体   繁体   中英

Change span based on select option data attribute

I have a select list which has a number of different options, each with a data attribute for price.

When a user selects an option, I'd like the contents of a span to change based on the data attribute from the selected option.

I have found a solution that updates an empty text field (item_price), but I could do with some help modifying this to change the contents of the span (new_price) as follows;

    <select class="item_size">
<option value="5 x 7" data-price="5.00">5 x 7 - <span>$ 5.00</span></option>
<option value="8 x 10" data-price="10.00">8 x 10 - <span >$ 10.00</span></option>
<option value="16 x 20" data-price="20.00">16 x 20 - <span>$ 20.00</span</option>
</select>
<input type="text" class="item_price" value="5.00"/>
    <span class="new_price"></span>

<script>
    $('.item_size').live('change', function(){

    var $this = $(this),
        selected = $this.find(':selected').data('price')

    $this.siblings('.item_price').val(selected);
    $this.siblings('.new_price').val(selected);

});
</script>

Also, I'm using jQuery 1.6.1 on this particular site.

Thank you.

use .text() / .html() as the target element is a span, .val() is used for setting the value of an input element

$this.siblings('.new_price').text(selected);

Demo: Fiddle

使用此而不是val

$this.siblings('.new_price').html(selected);

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