简体   繁体   中英

Javascript “If, else if, else with multiple conditions”

The following code increases the quantity of men on a move job to keep the total hours under 9 hours. This code works fine. ( http://economymoving.net/get_an_online_moving_quote.php )

// determines # of men needed to stay <= 9 hours and sets a 2 man minimum
            var menQty;

        if (Math.ceil(manHrs/9) < 2) {
            menQty = 2;
        }else{
            menQty = Math.ceil(manHrs/9);
        }

However, if there is a bulky item on a job there should be a minimum of 3 men. So I added the following code to the original working statement to check for bulky items. The code should check for bulky items. 1st test: If there are no bulky items AND manHrs/9 < 2 = a quantity of 2 men is set.
2nd test: If there are bulky items AND manHrs/9 <2 = a quantity of 3 men is set.

// determines # of men needed to stay <= 9 hours and sets a 2 man minimum
**// Also determines if there is a bulky item if true sets a 3 man minimum**    
    var menQty;

    if **(countBLKY = 0 &&** (Math.ceil(manHrs/9) < 2)**)**
    {
        menQty = 2;
    }
    **else if (countBLKY != 0 && (Math.ceil(manHrs/9) < 2))
    {
        menQty = 3;
    }**
    else
    {
        menQty = Math.ceil(manHrs/9);
    }

The script executes the ELSE section of code. I think there is a syntax issue because the function below should set the countBLKY variable to 0 or another integer.

Here is the function that feeds the countBLKY variable. The function seems to work fine and when viewed on the webpage the Bulky Item section shows either 0 or a greater number. (Large item tab on the webpage)

function addBLKY() {

    var bbyG = document.moveQuote.BLKY_babyGrandPiano.value * 1;
    var spnt = document.moveQuote.BLKY_SpinetPiano.value * 1;
    var uprt = document.moveQuote.BLKY_uprightPiano.value * 1;
    var bgtv = document.moveQuote.BLKY_bigScreenTV.value * 1;
    var pTbl = document.moveQuote.BLKY_poolTable.value * 1;
    var pBall = document.moveQuote.BLKY_PinballVideoGame.value * 1;

    var countBLKY = bbyG + spnt + uprt + bgtv + pTbl + pBall;

    document.moveQuote.BLKY_total.value = countBLKY;
}

I hope everything is clear, let me know if there is anything that isn't.

 if (countBLKY = 0 && (Math.ceil(manHrs/9) < 2)) // ^ 

That's an assignment, not a comparison . Also, you should shorten your code to:

var menQty = Math.ceil(manHrs/9);

if (countBLKY == 0)
    menQty = Math.max(menQty, 2); // at least two
else
    menQty = menQty < 2 ? 3 : menQty; // instead of one send three but two are OK

Notice the oddity with the minimum mancount for bulky items, you probably have a bug in your code there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM