John Arellano
John Arellano

Reputation: 173

Trigger event when selecting in a dropdown javascript eventlistener

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.

Upvotes: 10

Views: 42471

Answers (3)

Tommaso Boggia
Tommaso Boggia

Reputation: 159

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.

Upvotes: 12

Viet Anh
Viet Anh

Reputation: 139

I've solved your problem here: https://jsfiddle.net/evL4cc5q/

var lastIndex = "";
function listQ(){
    var e = document.getElementById("list");
    if(e.selectedIndex > 0){
        if(e.selectedIndex != lastIndex) {
            if("Blank Test" === e.options[e.selectedIndex].value)
                alert("yo");
            lastIndex = e.selectedIndex;
        }
        else {
            lastIndex = "";
        }
     }
}
document.getElementById("list").addEventListener("click",listQ);

Upvotes: 0

Jonathan
Jonathan

Reputation: 6537

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/

Upvotes: 3

Related Questions