user3587300 user3587300 - 3 years ago 198
HTML Question

Multiply Dropdown Field to Text Field in Javascript

Trying to create a calculator of sorts by using drop-down menus and quantities. How can I multiply the value from a drop-down to a text field, and have the result show up in another text field, using Javascript? This would apply to each line in the table.


<table width="594" border="1">
<th colspan="2" scope="col"><strong>Line Breakdown</strong></th>
<th colspan="2" scope="col"><strong>Qty</strong></th>
<th width="90" scope="col">Unit Line Cost</th>
<th width="90" scope="col">Total Line Cost</th>
<td width="122"><strong>Cabinets</strong></td>
<td width="150"><select name="DDcabinets" id="DDcabinets">
<option value="">Select an option …</option>
<option value="100">Dura Supreme</option>
<option value="110">Lenape Village</option>
<option value="120">Wellborn Forest</option>
<td width="65"><input type="text" name="Qcabinets" id="Qcabinets" size="10" maxlength="5"/></td>
<td width="41">ft.</td>


window.onload = function () {
var select1 = document.getElementById('DDcabinets');
var input1 = document.getElementById('Vcabinets');
select1.onchange = function () {
input1.value = select1.value;

I added this Javascript, but it's not working - I'm guessing my Javascript math is a bit off (that and I'm just really unfamiliar with the coding.)

var total1 = document.getElementById('Tcabinets');
var qty1 = document.getElementsById('Qcabinets');
qty1.onchange = function () {
total1.value = select1.value * qty1.value;

Also see for the full script. [NOTE: You may have to adjust the size of the "Output" column to see the entire table of dropdowns and textfields.]

Answer Source

Okay so you're SUPER close, great job! The two things that you need to take note of are this.

// getElement(s)ById, no such thing! Change it to getElementById
var qty1 = document.getElementsById('Qcabinets');

The next thing, is the element values are stored as string, you need to convert them to integral values, I tend to do this with parseFloat, but parseInt is just as good of a choice.

Just change your multiplication to convert the strings to integrals, and you're fine!

total1.value = parseFloat(select1.value) * parseFloat(qty1.value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download