3

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.

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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/

2 Comments

This is for a class assignment where most of the assignment we are essentially learning ourselves, but we're not allowed to use Jquery, react, unfortunately.
Yeah can be easily done in JS too, can't quite remember the steps though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.