js select on change value

JS Select On Change Value

If you are working with web development, you might have come across a situation where you want to execute a certain piece of code when the value of a select element changes. In JavaScript, we can detect the change event of a select element using onChange event attribute.

Let's say you have a select element in your HTML code:

<select id="mySelect">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

Now, you want to trigger an action when the user changes the selected option. You can add the onChange event attribute to the select element and specify the name of the function to be executed:

<select id="mySelect" onChange="myFunction()">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

Now, define the myFunction() function in your JavaScript code:

<script>
function myFunction() {
  var selectElement = document.getElementById("mySelect");
  var selectedValue = selectElement.options[selectElement.selectedIndex].value;
  console.log(selectedValue);
}
</script>

In this function, we first get the select element using its ID and then get the selected option using the selectedIndex property. Finally, we get the value of the selected option using the value property.

Alternative way:

Another way to achieve the same result is by using event listeners. You can add an event listener to the select element and listen for the change event:

<select id="mySelect">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

<script>
var selectElement = document.getElementById("mySelect");
selectElement.addEventListener("change", function() {
  var selectedValue = selectElement.options[selectElement.selectedIndex].value;
  console.log(selectedValue);
});
</script>

In this code, we first get the select element using its ID and then add an event listener to it. When the change event occurs, the function inside the event listener is executed, which gets the selected option and its value just like in the previous example.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe