Skip to content Skip to sidebar Skip to footer

Shipping Calculator, What Am I Missing In This Code To Make It Work?

Hello I am pretty new to this and I am trying to make this shipping calculator code work. This is what I have so far.

Solution 1:

Change your onclick code to:

calculateShipping(document.getElementById('price').value);

Edit, try this code, it should work:

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"ent"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"><head><title>Calculate Shipping</title><scripttype="text/javascript">/* <![CDATA[ */var price = 0;
var shipping = calculateShipping(price);

functioncalculateShipping(price){
var result = 0;
if (price <= 25){
    result = 1.5;
}
else{
    result = price * 10 / 100;
}
var total = result + (price - 0);
window.alert("Shipping is $" + result + ".  Total is $" + total +".");
} 

/* ]]> */</script></head><body><p>Purchase Price: $
<inputtype="text"name="price"id="price" /><inputtype="button"value="Calculate Shipping"onclick="calculateShipping(document.getElementById('price').value);" /></p></body></html>

Solution 2:

I think the best approach (without using any library, like JQuery) is the following:

<!DOCTYPE html><html><head><title>Calculate Shipping</title><scripttype="text/javascript">window.addEventListener('load', function(){
  var priceField = document.getElementById('price');
  var calculateButton = document.getElementById('calculate');
  var totalField = document.getElementById('total');

  calculateButton.addEventListener('click', function(){
    var price = parseInt(priceField.value);
    var shipping = calculateShipping(price);
    var total = price + shipping;

    totalField.value = "Your total is $" + total + ".";
  });

  functioncalculateShipping(price){
    return (price <= 25) ? 1.5 : price / 10;
  }
});


</script></head><body><h1>Purchase Price:</h1><label>Price:</label><inputtype="text"id="price" /><buttonid="calculate">Calculate Shipping</button><label>Total:</label><inputtype="text"id="total"disabled="disabled" /></body></html>

here I introduce some good practices, like:

  • Don't pollute the global namespace
  • Avoid inline Javascript (binding your event listeners as HTML attributes)
  • Avoid, if possible, the use of native message boxes (alert, confirm, prompt...), they're terribly intrusive, ugly and not customizable.

Post a Comment for "Shipping Calculator, What Am I Missing In This Code To Make It Work?"