Rusty Shackleford Rusty Shackleford - 1 month ago 14
HTML Question

Trouble getting a sum?

For some reason, my code just does not want to calculate. I'm working out of a practice book, but it is not really helping me in this regard. For the sum I get something like 20000NaN, which I know is not a number. How can I get it to calculate correctly? I tried using ParseFloat to convert my percentages. Thank you.

<form action="#" name="car">
<p>&nbsp;</p>
<p>Vehicle:
<select id="dropDown1">
<option selected value="370z, 20000, 10%, 8.5%">Accord</option>
<option value="M3, 18000, 8%, 8.5%">Altima</option>
<option value="Camaro, 19000, 9%, 8.5%">Camry</option>
</select>
<br />
<br />
</p>
<button type="button" onclick="car()" value="Submit">Book it now</button>
<br />
<br />
<textarea name="answer" cols="80" rows="3" disabled></textarea>
<br />
<br />
</form>
</div>

<script language="javaScript">
function car() {
var value = document.getElementById("dropDown1").value;
var split = value.split(",");
var v1 = split[0];
var v2 = split[1];
var v3 = split[2];
var v4 = split[3];
parseFloat(v3);
parseFloat(v4);
profit = v2*v3;
tax = v2*v4;
extra = profit+tax;
sum = v2 + extra;

document.car.answer.value = "You selected " + v1 + " " + "which has a base price of" + v2 + ", a profit of" + v3 + ", and sales tax of" + v4 + "." + " Total cost of this vehicle, including profit and sales tax is: $" + sum + "."

}

</script>

Answer

Most of your syntax was not right. This is how it should be:

var test = function() {
        var value = document.getElementById("dropDown1").value;
        var split = value.split(",");
        var v1 = split[0];
        var v2 = split[1];
        var v3 = split[2];
        var v4 = split[3];
        v3 = parseFloat(v3);
        v4 = parseFloat(v4);
        var profit = parseFloat(v2)*parseFloat(v3)/100;
        var tax = parseFloat(v2)*parseFloat(v4)/100;
        var extra = parseFloat(profit)+parseFloat(tax);
        var sum = parseFloat(v2) + parseFloat(extra);
document.getElementById("answer").value = "You selected " + v1 + " " + "which has a base price of $" + v2 + ", a profit of " + v3 + "%, and sales tax of " + v4 + "%. Total cost of this vehicle, including profit and sales tax is: $" + sum + ".";
    };
<form action="#" name="car">
        <p>&nbsp;</p>
        <p>Vehicle:
          <select id="dropDown1">
            <option selected value="370z, 20000, 10%, 8.5%">Accord</option>
            <option value="M3, 18000, 8%, 8.5%">Altima</option>
            <option value="Camaro, 19000, 9%, 8.5%">Camry</option>
          </select>
        <br />
        <br />
        </p>
        <button type="button" onclick="test()" value="Submit">Book it now</button>
        <br />
        <br />
        <textarea id="answer" cols="80" rows="3" disabled></textarea>
        <br />
        <br />
    </form>

Comments