developer
developer

Reputation: 5478

Dynamic HTML value calculation using JQuery/Javascript

I wanted to create a table where dynamic values are displayed in a column depending on values selected by users. Below is my code for it. So basically, depending on the number of adults and number of children that are selected, the Price will be calculated. So if someone chooses 1 adult and 0 children, then the Amount for 2 Day ticket should be $235, for 3 day it will be $301 and so on. I want this done on selection change method of selectboxes. I am also not very familiar with JQuery. How do I accompalish this using JQuery?

Ages 10+:


<select id="Adult" name="Adult">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>



Ages 3-9:

<select id="Child" name="Child">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>

<table width="800" border="1" align="center">
  <tr>
    <td width="224">Product</td>
    <td width="246">Ages 10+</td>
    <td width="192">Ages 3-9</td>
    <td width="110">Price</td>
  </tr>
  <tr>
    <td>2 Day Ticket</td>
    <td>$235.00</td>
    <td>$223.00</td>
    <td>$<span class="amount"></span> </td>
  </tr>
  <tr>
    <td>3 Day Ticket</td>
    <td>$301.00</td>
    <td>$285.00</td>
    <td>$<span class="amount"></span></td>
  </tr>
  <tr>
    <td>4 Day Ticket</td>
    <td>$315.00</td>
    <td>$298.00</td>
    <td>$<span class="amount"></span></td>
  </tr>
  <tr>
    <td>5 Day Ticket</td>
    <td>$328.00</td>
    <td>$309.00</td>
    <td>$<span class="amount"></span></td>
  </tr>
</table>

Upvotes: 0

Views: 2972

Answers (1)

Mark Meyer
Mark Meyer

Reputation: 3723

Here is complete code to accomplish what you're trying to do. I added some id's to the totals. See the fiddle for a working example. It would be better to not hard code the values, but this works as a starting point.

var numAdult = 0;
var numChild = 0;

$("#Adult").change( function(){
    numAdult = $("#Adult").val();
    calcTotals();
});
$("#Child").change( function() {
    numChild = $("#Child").val();
    calcTotals();
});

function calcTotals(){
    $("#2DayTotal").text(235*numAdult + 223*numChild);
    $("#3DayTotal").text(301*numAdult + 285*numChild);
    $("#4DayTotal").text(315*numAdult + 298*numChild);
    $("#5DayTotal").text(328*numAdult + 309*numChild);
}

Upvotes: 3

Related Questions