Pregunta

I've been using code from this question to create something very similar, the only thing I want to change is the calculation to get a different total result.

In that example they take the first value times the other and then echo out the result.

Taking the first value times the second works very well, but when I try to make the calculation more advanced it all fails.

I want to be able to make the following equation with the selected values:

var total = ((firstSelect*secondSelect)-firstSelect*0,68)*300;
alert(total);

I've also tried the following and this too fails:

var oppa = firstSelect * rate;
var gagnam = secondSelect * 0.68;
var style = oppa - gagnam;
var total = style * 300;

alert(total);

Currently my HTML looks like this:

<p>Number of sales</p>
 <select name="firstSelect" id="firstSelect" class="DoPricing">
    <option value="15">15</option>
    <option value="20">20</option>
    <option value="25">25</option>
    <option value="30">30</option>
    <option value="35">35</option>
    <option value="40">40</option>
    <option value="45">45</option>
    <option value="50">50</option>
    <option value="55">55</option>
    <option value="100">100</option>
    <option value="150">150</option>
 </select>

 <p>Times rate</p>
 <select name="secondSelect" id="secondSelect" class="DoPricing">
    <option value="0.99">0.99</option>
    <option value="1.15">1.15</option>
    <option value="1.5">1.5</option>
    <option value="2">2</option>
    <option value="2.5">2.5</option>
    <option value="3">3</option>
 </select>
<br>
<br>
<input type="submit" name="submit" value="submit" id="submit">

and my JS

function calc() {
    var total,
    nSales,
    rate;

    var nSales = document.getElementsByName("firstSelect")[0].value;
    var rate = document.getElementsByName("secondSelect")[0].value;

    var oppa = nSales * rate;
    var gagnam = rate * 0.68;
    var style = oppa - gagnam;

    var total = style * 300;

    alert(total);
    }

    window.onload = function () {
    document.getElementById("submit").onclick = calc;
};

How would I go about to accomplish this?

¿Fue útil?

Solución

You have the onclick handler inside the calc() function, you should have it outside so it add the event listener on windows.onload

function calc() {
    var total,
    nSales,
    rate;
    var nSales = document.getElementsByName("firstSelect")[0].value;
    var rate = document.getElementsByName("secondSelect")[0].value;
    var oppa = nSales * rate;
    var gagnam = nSales* 0.68;  //changed to nSales
    var style = oppa - gagnam;
    var total = style * 300;
    alert(total);
};
window.onload = function () {
    document.getElementById("submit").onclick = calc;
}

Demo here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top