Sergi Sergi - 2 months ago 8
Javascript Question

Simple Jquery if/else like

I'm missing something very simple here, I'm aware there's no if/else in JQuery but how can I do the same with this code?

$("#dropDown").val("vegetables");
$(newEl).css("background-color", "green");

$("#dropDown").val("meatFish");
$(newEl).css("background-color", "red");


Basically, I want it to say, if the dropDown value is "vegetables" then apply that css value, if it's "meatFish" then apply that other css.

Answer

You can use if else from JavaScript and val() from jQuery:

if($("#dropDown").val() == "vegetables") {
  $(newEl).css("background-color", "green");
} else if ($("#dropDown").val() == "meatFish") {
  $(newEl).css("background-color", "red");
}