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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元