填写表单的脚本执行速度比onchange()更快,可以显示表单的选项

时间:2016-08-30 17:19:49

标签: javascript forms

我正在使用Javascript书签来自动填写页面上的表单。给出的一些选项是下拉选项,根据使用onchange()选择的内容显示不同的选项。我有类似的代码:

/* Gets first drop down and sets value to first in list */
var dropDown1 = document.getElementById("dropDown1Name");
dropDown1.value = "option1InDropDown";
dropDown1.onchange();

/* Sets value of second drop down to option that is available when first option in first drop down is selected */
var dropDown2 = document.getElementById("dropDown2Name");
dropDown2.value = "optionRevealedByDropDown1Change";

但是这不起作用,因为onchange()在我将其设置为值时不会填充第二个下拉列表。当脚本完成执行时,dropDown2中没有设置值。我已经尝试了几种方法使代码“等待”但我找不到正确的解决方案。任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:3)

将第一个<select>change事件绑定,类似<select>,但会立即触发。要将第一个<select>的值同步到第二个var s1 = document.getElementById('s1'); var s2 = document.getElementById('s2'); s1.addEventListener('input', function(e) { var idx = this.selectedIndex; var data = idx.value; s2.selectedIndex = idx; }, false);的选项,请在事件处理程序中使用input属性。

&#13;
&#13;
label {
  margin-left: 6ex;
}
&#13;
<fieldset>
  <legend>Binding Input Event</legend>
  <select id='s1'>
    <option>---</option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
  </select>

  <select id='s2'>
    <option>---</option>
    <option value='A'>A</option>
    <option value='B'>B</option>
    <option value='C'>C</option>
  </select>


</fieldset>
&#13;
why <- data.frame(sensitivity = c(5, 6, 7, 7, 8, 9), perspective = c(1, 1, 1, 0, 0, 0))
ttestBF(sensitivity ~ perspective, data = why)
t.test(sensitivity ~ perspective, data = why)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

正如评论中已经指出的那样,问题的一部分是错误触发change事件。问题的另一部分可能是第二个下拉列表的选项只有在收到某些异步操作的结果后才会填充(例如使用XMLHttpRequest)。在这种情况下,即使正确触发了change事件,您的代码仍需要等待下拉列表才能在设置值之前填充。如果下拉列表中填充了值(例如,使用setIntervalsetTimeout),则一种方法可能基于定期检查。更优雅的方法可以使用MutationObserver等待下拉列表来填充值。看一下这个片段:

var sel1 = document.querySelector('#sel'),
  sel2 = document.querySelector('#sel2');

// Onchange code
sel1.addEventListener('change', function() {
  sel2.disabled = false;
  // emulate async request for dropdown options
  setTimeout(function populateSecondSelect() {
    ['', 'dynamic1', 'dynamic2'].forEach(function(val) {
      var opt = document.createElement('option');
      opt.setAttribute('value', val);
      opt.textContent = val || '-';
      sel2.appendChild(opt);
    });
  }, 2000);
});

// Code to trigger events (based on http://stackoverflow.com/a/2490876/2671392)
function triggerEvent(type, element) {
  var event; // The custom event that will be created

  if (!!window.Event) {
    event = new Event(type);
  } else if (document.createEvent) {
    event = document.createEvent("HTMLEvents");
    event.initEvent(type, true, true);
  } else {
    event = document.createEventObject();
    event.eventType = type;
  }

  event.eventName = type;

  if (document.createEvent) {
    element.dispatchEvent(event);
  } else {
    element.fireEvent("on" + event.eventType, event);
  }
}

document.querySelector('#btn').addEventListener('click', function() {
  sel1.value = sel1.value === '1' ? '2' : '1';
  // trigger change event
  triggerEvent('change', sel1);
  // set MutationObserver for second dropdown
  var observer = new MutationObserver(function(mutations) {
    sel2.value = 'dynamic2';
    observer.disconnect();
  });
  // only observe changes in the list of children
  var observerConfig = {
    childList: true
  };
  observer.observe(sel2, observerConfig);
});
<div>
  <input type="button" id="btn" value="Select values" />
  <select id="sel">
    <option value="" selected>-</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
  </select>
  <select id="sel2" disabled>
  </select>
</div>

但请注意,MutationObserver在旧版浏览器中不可用。