javascript – How to calculate the total cost using conditional statements?-ThrowExceptions

Exception or error:

I am going to show the tour prices which varies with the number of adults and children.

Example.

when user input,

A.

Adults 1 — result should show US$ 60

Adults 2 — result should show US$ 100

Adults 3 — result should show US$ 120

B.

Child 1 — result should show US$ 15

Child 2 — result should show US$ 24

Child 3 — result should show US$ 30

C.

Total should be X+Y

That means,

If user input adults 2 and child 3 the total should show US$ 130

I made up to get x & y. But I do not know whether it is totally correct. I couldn’t present the code here, it says “Your post appears to contain code that is not properly formatted as code”

How can I get the total?

How to solve:

You can use JavaScript with HTML to start with. I gave sample code below. However,for any practical purposes I recommend doing calculations on server side with ajax or other means.

<!DOCTYPE html>
<html>
<body>

<script>
<!--
function setTicketCost(){
    var adultCost = parseInt(document.getElementById('adults').value);
    var childrenCost = parseInt(document.getElementById('children').value);
    var totalCost = adultCost + childrenCost;
    document.getElementById('cost').innerHTML = "<b>" + totalCost + "</b>";
}
-->
</script>

<h2>Ticket Sales</h2>

<p>Select number of Adults and Children from below drop-down lists:</p>

  <label>Choose Number of Adults:</label>
  <select id="adults" name="adults" onchange="setTicketCost();">
    <option value=0>0</option>
    <option value=60>1</option>
    <option value=100>2</option>
    <option value=120>3</option>
  </select>
  <br/>
  <label>Choose Number of Children:</label>
  <select id="children" name="children" onchange="setTicketCost();">
    <option value=0>0</option>
    <option value=15>1</option>
    <option value=24>2</option>
    <option value=30>3</option>
  </select>
  <br/>
  <br/>
  <label>Total Cost: </label>
  <label id="cost" name="cost"></label>

</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *