flinx777
flinx777

Reputation: 597

jQuery math on selection change

So using jQuery I was able to figure out how to change the value of HTML in a span on change with a selection drop down, but it's a bit hacky. Here's the code: http://jsfiddle.net/flinx777/ZMjun/

Currently I'm grabbing the class from the selection chosen and replacing the text in the span with the class value. Instead I'd prefer to define the span HTML (define the price of the product here) and when someone chooses from the selections, it either adds or subtracts from the price. So for example I'm trying to make the selection HTML like this:

<select id="price_change" name="buckle options">
<option value="" class="">Please select</option>
<option value="Stainless steel" class="">Stainless Steel</option>
<option value="Titanium" class="+20">Titanium</option>
<option value="No Buckle" class="-10">No Buckle</option>
</select>

This way I can define in the class in the selection options to either add or subtract from the product price (which is in the span) as opposed to the current way I'm doing it of having to manually do the math in the selection as I'm doing now.

Thanks!

Upvotes: 1

Views: 416

Answers (4)

ZolaKt
ZolaKt

Reputation: 4719

This works
http://jsfiddle.net/Vw5Ms/5/

But man, this is soooo dirty

Upvotes: 0

Nery Jr
Nery Jr

Reputation: 4009

You can use the property "value"

<select id="price_change" name="buckle options">
    <option value="135" >Please select</option>
    <option value="135" >Stainless Steel</option>
    <option value="155" >Titanium</option>
    <option value="125" >No Buckle</option>
</select>

Change the code that you proposed to:

$(document).ready(function(){
    //Changes the price on the page if a selection is made with a price modifier
    $("#price_change").change(function() {
        var price = $(this).children("option:selected").val();
        $(".product_price").html(price);
    });
});

Upvotes: 6

Beno&#238;t
Beno&#238;t

Reputation: 7427

You can try something like this:

http://jsfiddle.net/Fft7G/

but in my opinion, it is stange to set price in class

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190996

You should make these data- attributes, not a class.

<select id="price_change" name="buckle options">
<option value="" data-offset="0">Please select</option>
<option value="Stainless steel" data-offset="0">Stainless Steel</option>
<option value="Titanium" data-offset="+20">Titanium</option>
<option value="No Buckle" data-offset="-10">No Buckle</option>
</select>

Then you can do.

var offset = parseInt($(someSelector).data('offset'), 10);

Upvotes: 4

Related Questions