0

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">
Rick
  • 9
  • 1
  • 5

2 Answers2

1

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?

Community
  • 1
  • 1
burtek
  • 2,576
  • 7
  • 29
  • 37
  • Thanks this worked however it's returning NaN - the £ symbol isn't factored into the numbers - could it be the decimal causing this? – Rick Mar 08 '17 at 12:44
  • 1
    Sorry I just saw the £ is in the hidden value. Works great thanks – Rick Mar 08 '17 at 12:46
1

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>
Joffutt4
  • 1,418
  • 14
  • 15