douzuan5365 2014-07-22 11:33
浏览 256

选择下拉列表项而不触发onchange事件?

I want to populate a drop-list with several items and select a default item:

<select onchange="DoSomething(this)">
    <option value="abb">This is the second item</option>
    <option value="abc" selected>This is the third item</option>
    etc...
</select>

However I don't want the onChange event to fire (or I want the code triggered by onChange to be ignored) until the user selects an item. At the moment the onChange event fires as the page loads and the selected item is chosen by default.

Can I wrap this code in PHP to achieve this - if so how?

  • 写回答

1条回答 默认 最新

  • dongyi8383 2014-07-22 12:30
    关注

    ?!

    Manipulating the HTML DOM directly in JavaScript doesn't fire events. You can even call myForm.submit() and the browser will not fire the form's onsubmit event, therefore bypassing client-side onsubmit validation.

    I don't know what you've tried, but this is one way to select for example the first item of the drop-down list:

    document.getElementsByTagName('select')[0].getElementsByTagName('option')[0].selected = true;
    

    (http://jsfiddle.net/Jawh6/)

    Crude, I know. Usually your forms and fields would be named or otherwise identified so you can address them more excplicitly: e.g. document.myForm.mySelect.options[0].selected = true;


    Since your PHP is already setting the 'selected' attribute on the option (or your question isn't very well tagged), this would be the best place to set the default option when the page loads, that requires no JavaScript at all.

    If you're interested in how to get PHP to write out the HTML for a select element and correctly assign the selected attribute to the intended option, I reckon you need to write a new question to attract the PHP folk.


    Either you have other calls to your DoSomething function, or you've oversimplified your example and you're actually using a framework to bind the event handler to the field and maybe you accidentally called your function instead of assigning it, e.g.:

    mySelect.onchange = DoSomething(); // oops, this calls DoSomething right away.
    
    mySelect.onchange = DoSomething; // this sets DoSomething as the event handler.
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100