duangu8264 2015-05-28 08:45
浏览 221
已采纳

如何更改下拉值并在javascript中触发onchange函数

I was wondering if it is possible to change a value of a dropdown box dynamically and to trigger an ajax onchange function assigned to this dropdown at the same time.

so far I can only change the value of a dropdown box but the onchange function is not being called.

here is the dropdown:

<select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
  <option value="">--Select Item--</option>
  <option value="one"> Option one</option>
  <option value="two"> Option Two</option>
  <option value="three"> Option Three</option>
</select>

when I do this operation:

document.getElementById("ProductSelector").value = "one";

the value of the dropdown is changing, but the getItems function is not being triggered.

What am I doing wrong or may be there is another way to change a value of the doropdown which will allow me to trigger my ajax function as well?

I don't want to use JQuery. I just wandering why the function is not working if I use dinamic change and on manual change it works fine?

  • 写回答

6条回答 默认 最新

  • dongpobo6009 2015-05-28 09:12
    关注

    So, you are changing the value with JavaScript and the change event isn't triggering. So, lets trigger it then.

    Trigger the event change every time you change the value via JavaScript.

    No jQuery used.

    Try this:

    function changeVal() {
      var elem = document.getElementById("ProductSelector"),
        event = new Event('change');
    
      elem.value = "one";
      elem.dispatchEvent(event);
    }
    
    
    function getItems(val) {
      alert(val);
    }
    
    changeVal();
    <select name="ProductSelector" id="ProductSelector" onchange="getItems(this.value)">
      <option value="">--Select Item--</option>
      <option value="one">Option one</option>
      <option value="two">Option Two</option>
      <option value="three">Option Three</option>
    </select>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?