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.


when user input,


Adults 1 — result should show US$ 60

Adults 2 — result should show US$ 100

Adults 3 — result should show US$ 120


Child 1 — result should show US$ 15

Child 2 — result should show US$ 24

Child 3 — result should show US$ 30


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>

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>";

<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>
  <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>
  <label>Total Cost: </label>
  <label id="cost" name="cost"></label>


Leave a Reply

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