I have this javascript function,
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if("Blank Test" === e.selectedIndex){ alert("yo"); }
}
}
My problem is how to trigger the function when selected the same value of dropdown list?
I tried this code,
document.getElementById("list").addEventListener("change",listQ);
And it must use an event listener.
The contextmenu event fires when the user attempts to open a context menu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key.
The HTML Select DropDownList has been assigned a jQuery OnChange event handler. When an item is selected in the HTML Select DropDownList, the jQuery OnChange event handler is executed within which the Text and Value of the selected item is fetched and displayed in JavaScript alert message box.
HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.
You can use the onchange
method on your select element.
var changedText = document.getElementById('changed');
function listQ(){
changedText.textContent = this.value;
}
document.getElementById("list").onchange = listQ;
For this HTML
<select id="list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<p>
Your value <span id="changed"></span>
</p>
Here is a Fiddle forked from Jonathan, and here is MDN documentation for the change event.
The line "Blank Test" isn't going to work because e.selectedIndex
is going to be an index (a number). You could use e.options[e.selectedIndex].value
Apart from that, just change the event listener to "click" instead of "change":
<select id="list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="Blank Test">Four</option>
</select>
<script type="text/javascript">
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if("Blank Test" === e.options[e.selectedIndex].value){ alert("yo"); }
}
}
document.getElementById("list").addEventListener("click",listQ);
</script>
Here's a Fiddle to demonstrate: https://jsfiddle.net/h81pcpm0/
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