Lachlan Jansen Lachlan Jansen - 2 years ago 89
Javascript Question

Multiplying in JS not working

I can't really explain my question but i am trying to create a total dollars on my website.
I am trying to multiply the quantity by the size.

function total(){
var x = document.getElementById("size").selectedIndex;
var y = document.getElementById("price");
var z = document.getElementById("price2");
var z = document.getElementById("quantity").value;
if ((document.getElementsByTagName("option")[x].value) == "XS") {
else if ((document.getElementsByTagName("option")[x].value) == "S") {
else if ((document.getElementsByTagName("option")[x].value) == "M") {
else if ((document.getElementsByTagName("option")[x].value) == "L") {
else if ((document.getElementsByTagName("option")[x].value) == "XL") {

This code makes the program not work altogether.

Any help appreciated, Lachlan

Answer Source

You haven't posted a mimial example that displays the issue, but likely one issue is how you're getting the value of x:

  var x = document.getElementById("size").selectedIndex;

that can be replaced with getting the value directly:

  var x = document.getElementById("size").value;

Then you have:

if (x == "XS") {
  else if (x == "S") {

and so on. But all those if..else statements can likely be replaced by switch.

Then there is code like:


I'm not sure what the dot is for, perhaps you are trying concatenation?

  y.innerHTML = "$" + (10.00 * a);
  z.value = "$" + (10.00 * a);

where a is a value from elsewhere? And if you want two decimal places, then:

  y.innerHTML = "$" + (10.00 * a).toFixed(2);

Oh, and note that an option can have a value that is different to the displayed text, so you can do:

  <option value="13.50">M</option>

So now you you can remove the if..else blocks and just have:

  y.innerHTML = "$" + (x * a).toFixed(2);

x will be a string, but multiplication will coerce it to a number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download