Skip to content

How to use If Else in OnChange() event in JavaScript?

This is My HTML code:

<select id="stand" onchange="myFun2()">
                <option value="platinumGallery">Platinum Gallery</option>
                <option value="superHospitalityStand">Super Hospitality Stand</option>
                <option value="northWestStand">North West Stand</option>
                <option value="eastStand">East Stand</option>
</select><br><br>

<label>Cost Of Ticket: </label>
<input id="costOfTicket" type="text" readonly>

And JS Code:

function myFun2(){
    var costOfTicket;
    var selectedStand = document.getElementById("stand").value;
    if(selectedStand = "platinumGallery"){
        costOfTicket = 25000;
    }
    else if(selectedStand = "superHospitalityStand"){
        costOfTicket = 20000;
    }
    document.getElementById("costOfTicket").value = costOfTicket;
}

Whenever onchange() event occurs I want to display Cost Of Ticket according to the selected value of select. But it shows 25000 after onchange() event and then never changes irrespective of the values selected. How to correct the code to complete above task?

Answer

Let me tell you. In the if-else statement, you are not comparing the values but in fact, you are assigning the values.

So change your if-else statement to:

if(selectedStand == "platinumGallery"){
        costOfTicket = 25000;
}
else if(selectedStand == "superHospitalityStand"){
        costOfTicket = 20000;
}