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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With