EnderFran2006
EnderFran2006

Reputation: 1

conditional dropdown menus

I am trying to figure out how to have that if you select something in my dropdown menu, It will write in the HTML 'You want .....'

Here is my code

function latte1() {
  if (document.getElementById("latte").click) {
    alert("You like Latte")
  } else {
    document.write("You like Something else")
  }
}
<option id="latte" onclick="latte1()">Latte</option>

Any help is appreciated

Upvotes: 0

Views: 143

Answers (3)

Jamiec
Jamiec

Reputation: 136124

You have to start with a <select> element which raises a change event when a selection is made. Inside that event, this.value refers to the selected value.

var drinkSelect = document.getElementById("drink");
var outputDiv = document.getElementById("output");
drinkSelect.addEventListener("change",function(){
  outputDiv.innerText = "You like " + this.value;
})
<select id="drink">
  <option value="">Which drink would you like?</option>
  <option>Latte</option>
  <option>Capuccino</option>
  <option>Americano</option>
  <option>Tea</option>
</select>
<div id="output"></div>

Upvotes: 1

poetrasapoetra
poetrasapoetra

Reputation: 175

I assume that you want use select dropdown and show selected option

function latte1(ele) {
  document.getElementById("selected_option").innerText = "You want " + ele.value;
}
<select onchange="latte1(this)">
  <option value="" disabled selected>Choose option</option>
  <option value="Latte">Latte</option>
  <option value="Something else">Something else</option>
</select>
<p id="selected_option"></p>

Upvotes: 0

sbgib
sbgib

Reputation: 5828

Try like this:

function latte1() {
  var latte = document.getElementById("latte");
  
  //the first latte below can be replaced with any other element
  latte.insertAdjacentHTML("afterend", "<p>" + (latte.click ? "You like Latte" : "You like Something else") + "</p>");
}
<option id="latte" onclick="latte1()">Latte</option>

This code identifies an element in the page (in this case #latte) and addes a <p> element after it containing your text.

Upvotes: 0

Related Questions