protommxx
protommxx

Reputation: 57

How to save select dropdown menu option in HTML/pure JS?

Let's say I have this code:

<select id = dropdown-list>
    <option value = "0"> Yes </option>
    <option value = "1"> No </option>
</select>

The user can select yes or no from a dropdown list. How can I use pure JS/HTML to figure out what the user has selected (and is currently showing in the dropdown list box when the list isn't expanded) so I can use that data elsewhere? The only way I can figure out is if I add an eventListener on each option but I feel there is a better way. I am quite new to JS so I'm not sure. Thank you.

Upvotes: 3

Views: 1924

Answers (3)

Kawser Habib
Kawser Habib

Reputation: 1422

Execute a JavaScript function changeResult when a user changes the selected option of a element:

Flow:

  1. We bind changeRegult using onchange event listener.
  2. When we change the dropdown menu, it calls changeResult function.
  3. Inside the function, we select our dropdown menu using its id property.
  4. After getting the element by id, we can now access all properties.
  5. Here we want to show the value property, so we use document.getElementById("dropdown-list").value.

For more check this link.

function changeResult() {
  var x = document.getElementById("dropdown-list").value;
  document.getElementById("result").innerHTML = "You selected: " + x;
}
<select id = "dropdown-list" onchange="changeResult()">
    <option value = "0"> Yes </option>
    <option value = "1"> No </option>
</select>
<p id="result"></p>

Upvotes: 0

Anonymous
Anonymous

Reputation: 4630

You may want to use on change event. Since you use each I suppose you are using Jquery. If you have any question just let me know.

$(document).ready(function(){
    $('#dropdown-list').on('change',function(){
    alert($(this).children('option:selected').val());
  })
});

https://jsfiddle.net/u4dz162o/

Upvotes: 0

Maverick Fabroa
Maverick Fabroa

Reputation: 1183

You can use onchange attribute from select element.

<select id="dropdown-list" onchange="onChange(this.value)">
    <option value = "0"> Yes </option>
    <option value = "1"> No </option>
</select>

and in JS:

function onChange(val) {
  // `val` is the value
}

Upvotes: 1

Related Questions