Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What event handler do I need to use for a drop down menu list in JavaScript?

I need to make an event handler to run my function each time a new item is selected from a drop down menu list.

So far I have tried "onselect", "onclick", "onmousedown", and "onblur" and none of these seem to work. What is the value needed to update each time someone selects a new item from the drop down menu list or the same item, for that matter?

like image 416
Smurfling Avatar asked Sep 13 '25 15:09

Smurfling


1 Answers

You need to use an onchange event handler, you can implement this with diffrent methods. The first one is to write the event directly in your html select tag:

function myFunction() {
    var x = document.getElementById("mySelect").value;
    document.getElementById("demo").innerHTML = "You selected: " + x;
}
<select id="mySelect" onchange="myFunction()">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>

Use Javascript only:

var mySelect = document.getElementById('mySelect');

mySelect.onchange = function() {
   var x = document.getElementById("mySelect").value;
   document.getElementById("demo").innerHTML = "You selected: " + x;
 }
<p>Select a new car from the list.</p>

<select id="mySelect">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>

Or you can use jQuery:

$("#mySelect").change(function() {
    $("#demo").html("You selected: " + this.value);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>

<select id="mySelect">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>

Alternatively for jQuery you can use the on function:

$("#mySelect").on("change", function() {
    $("#demo").html("You selected: " + this.value);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>

<select id="mySelect">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>
like image 138
Rudie Visser Avatar answered Sep 16 '25 05:09

Rudie Visser