Call function on specific dropdown selection

时间:2019-04-08 13:47:34

标签: javascript dropdown

I am trying to call a simple function on a specific option selection in a dropdown menu.

In this example, I want to the function to execute only when the 4th option is selected

<select onchange="if (this.selectedIndex = 4) mypopup();">
<option value="1">P1</option>
<option value="2">P2</option>
<option selected="selected" value="3">P3</option>
<option value="4">P4</option>
</select>

4 个答案:

答案 0 :(得分:1)

You need a function when the onchange event is triggered and you need to check what's option selected and than you can simply trigger your other function.

function selectChange(ev){
  const value = ev.target.value;
  if(value === 3){
    myPopup(); // call your function
  }
}
<select onchange="selectChange(event)">
<option value="1">P1</option>
<option value="2">P2</option>
<option value="3">P3</option>
<option value="4">P4</option>
</select>

答案 1 :(得分:1)

you need to check index as below to check the 4th option is selected .

<select onchange="if (this.selectedIndex == 3){ mypopup();}">
<option value="1">P1</option>
<option value="2">P2</option>
<option selected="selected" value="3">P3</option>
<option value="4">P4</option>
</select>

答案 2 :(得分:0)

It's very simple.

First you need to use this.value instead of this.selectedIndex.

Second thing is you must use == to test equality, instead of = to set a new value

let mypopup = function() {
  alert("Popup")
}
    <select onchange="if (this.value == 4) mypopup();">
      <option value="1">P1</option>
      <option value="2">P2</option>
      <option selected="selected" value="3">P3</option>
      <option value="4">P4</option>
    </select>

答案 3 :(得分:-1)

I would suggest to handle in your function only.

myPopup(e, id){

  if(id==4)
    //todo
  }
  else{
    //stop the event
    e.stopPropagation();
  }
}