• 0

[JavaScript] Showing Amount based on Rate


Question

Hi

Look at the picture below.

post-85578-1164555495_thumb.jpg

Ok, I give you some example. If the user select 5 hours, then the total cost should be $100. But if the user select to 3 hours later, then it should be $60 ($20 * 3) as $20 is default as per hour.

Here is my incompleted and sample code

<select name="hourly" onchange="calculate.totalcost.value = eval(calculate.totalcost.value * calculate.hourly.value)">
...
</select>

$<input type="text" name="totalcost" value="20" size="5" disabled />

You can notice that the Input text for Total Cost is disabled. The calculation has to be done by JavaScript so the user can't directly edit it before the form can be submitted.

Anyway, I am not sure about how to code it correctly as whenever I changed the option from DropDown List, for e.g. when I selected 7 hours, then $20 became $140. However, when I selected 2 hours, it became $280 ($40 was supposed to be displayed instead of $280). I am not sure about implementing the correct code for JavaScript. Anyone who can help with this? Thanks

It's very simple one. :rolleyes:

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

This is why u are getting the wrong values

<select name="hourly" onchange="calculate.totalcost.value = eval(calculate.totalcost.value * calculate.hourly.value)">
...
</select>

You are never clearing the value stored in the "calculate.totalcost" text box

Try this instead:

<select name="hourly" onchange="calculate.totalcost.value = eval(calculate.hourly.value * 20)">
...
</select>

Probably best having a constant instead of hardcoding the "20" value, so it can be changed at a later date more easilly

Link to comment
Share on other sites

  • 0

Thanks for your fast reply. It perfectly works. :D

I never think of that as I had spending alot of time wondering why the value became too bigger whenever I changed the option from dropdown list. :blush:

Ok I have put the code below inside a PHP webpage.

<?php
$cost = $_GET['cost'];
...

echo '<select name="hourly" onchange="calculate.totalcost.value = eval('.$cost.' * calculate.hourly.value)">';
...
echo '$<input type="text" name="totalcost" value="'.$cost.'" size="3" maxlength="5" disabled />';

Everything is OK already. Thanks guys for your help! (Y)

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.