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条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?