Switch Case



Testa kodexemplet:


Kodexempel

<select id="weatherSelect" class="form-select mb-3">
    <option value="">--Select Weather--</option>
    <option value="sunny">Sunny</option>
    <option value="rainy">Rainy</option>
    <option value="snowing">Snowing</option>
    <option value="overcast">Overcast</option>
</select>
<p id="weatherAdvice" class="h5"></p>
<script>
// This example demonstrates how to use conditional logic to display different messages 
//based on the selected weather condition
//querySelector is used to select elements in this case a select element with id "weatherSelect" 
// and a paragraph with id "weatherAdvice"
const select = document.querySelector("#weatherSelect");
const para = document.querySelector("#weatherAdvice");

//change is an event that is triggered when the selected option in the dropdown changes
select.addEventListener("change", setWeather);

// setWeather is a function that updates the paragraph text based on the selected weather condition
// It is called when the change event occurs
function setWeather() {
    const choice = select.value;
    //The switch statement checks the value of choice against each case and executes the corresponding code block. 
    switch (choice) {
      //
      case "sunny":
        para.textContent = "It's sunny! Wear shorts and go to the beach!";
        break;
      case "rainy":
        para.textContent = "Rain is falling - take an umbrella!";
        break;
      case "snowing":
        para.textContent = "Snow is coming down - build a snowman!";
        break;
      case "overcast":
        para.textContent = "Grey skies - take a rain coat just in case.";
        break;
      default:
        para.textContent = "";
        break;
    }
}
</script>