Rick
Rick

Reputation: 9

Javascript onselect change price

I'm trying to update the price of a product if the user selects an optional extra using a dropdown box. It's supposed to update the hidden field as well as the H1 tag which shows the user the new price. It doesn't appear to work.

function xDeckIncreasePrice(price) {
var total = document.getElementById("agreedPrice").value;
var newprice = Number(total) + Number(price); 
document.getElementById("mixingDeckTotal").innerHTML = "£" + newprice + "";
document.getElementById("agreedPrice").value = "£" + newprice + "";
}

Here is the HTML:

 <select name="size">
  <option value="6inch">6 Inch</option>
  <option value="footlong" onselect="xDeckIncreasePrice('2.50')">Footlong (+£2.50)</option>
</select>

And here are the elements to be updated:

<h1 style="color:red;" id="mixingDeckTotal">£4.50</h1><p>
<input type="hidden" id="agreedPrice" value="£4.50">

Upvotes: 0

Views: 210

Answers (2)

Joffutt4
Joffutt4

Reputation: 1458

You should change the onselect event to an onchange event on the actual select element itself. You should also change the select options to have a value of the price that the option represents. Then you should change the event you call to just set the text to the value of the option selected.

function xDeckChangePrice(element) {
  document.getElementById("mixingDeckTotal").innerHTML = "£" + element.value + "";
}
<select name="size" onchange="xDeckChangePrice(this)">
  <option value="4.5">6 Inch</option>
  <option value="7">Footlong (+£2.50)</option>
</select>

<h1 style="color:red;" id="mixingDeckTotal">£4.50</h1>

Upvotes: 1

burtek
burtek

Reputation: 2685

Apart from using £ in the prices, which won't work for numbers in JavaScript, <option> tag does not support onselect event. You should use <select>'s onchange event for that.

Similar question: How to use onClick() or onSelect() on option tag in a JSP page?

Upvotes: 1

Related Questions