更改<select option>在Javascript中,但之前的选择保留,为什么?

Changing the content of a <select option> in Javascript but previous selection stays, why?

本文关键字:保留 为什么 选择 select option Javascript 更改      更新时间:2023-09-26

我正在尝试做一个简单的脚本,检查日期,如果"选择的日子" == "明天"然后更改包含交付选项的下拉菜单:

Drop down: 0-When?(selected) 1-AM 2-PM

如果day = tomorrow,那么我删除javascript中的选项:

Drop down: 0-When? 2-PM(selected)

脚本:

// remove all options first
document.getElementById('inputheurelivraison').options.length = 0;
if (parseInt(datebits[2]) == parseInt(demain)){//remove am
  document.getElementById('inputheurelivraison').options[0] = new Option("WHEN?", 0, false, false);
  document.getElementById('inputheurelivraison').options[1] = new Option("PM", 2, true, true); // new Option(text, value, defaultSelected, selected)
  alert ("<? echo t(73); ?>");
}
else {//put am
  document.getElementById('inputheurelivraison').options[0] = new Option("WHEN?", 0, true, true);
  document.getElementById('inputheurelivraison').options[1] = new Option("AM", 1, false, false);
  document.getElementById('inputheurelivraison').options[2] = new Option("PM", 2, false, false);
}

问题:

假设有人填写表单,然后选择"AM"作为选项,然后将日期更改为"明天",然后我的脚本运行并从列表中删除"AM"选项,并选择"PM"作为"selected"。当用户提交表单时,POST数据是选中的"AM"…

为什么?我选择了"PM",当我看一看HTML时,它说"PM"为"selected",那么为什么它不提交该值呢?

Thanks a bunch in advance

没有必要先删除所有选项,您可以只删除不需要的选项。像下面这样的东西应该是合适的(注意存储对DOM元素的引用,所以只能得到一次):

var doIt = (function() {
  // Reference to removed option
  var removedOption;
  return function(s) {
    // Get reference to select once
    var select = document.getElementById('inputheurelivraison');
    if (parseInt(datebits[2]) == parseInt(demain)) {
      // Store reference to am option then remove it
      removedOption = select.options[1];
      select.removeChild(select.options[1]);
      // Make pm selected (it's now index 1)
      select.options[1].selected = true;
      // Debug?
      alert ("<? echo t(73); ?>");
    } else {
      // Replace removed option
      select.insertBefore(removedOption, select.options[1]);
      // Make first option selected
      select.options[0].selected = true;
    }
  }
}());

也可以将不需要的选项移动到隐藏的select元素中。

以上只是一个概念证明的例子,有很多方法可以给猫剥皮,底线是你不必每次都删除所有的选项并重新创建你想要的

谢谢你的回答。但我刚刚发现了问题所在。我来解释一下,以防对其他人有帮助。

检查"day"是否="tomorrow"并更改表单后,脚本将用AJAX将数据POST到PHP文件中。所以这里是问题的起源:我要求我的脚本POST我的下拉框的selectedIndex而不是它的option[selectedIndex].value。出于这个原因,我的脚本返回"AM"作为选择,即使"PM"被选中,因为selectedIndex总是从0,1,2等开始,我的value是AM=1和PM=2。

所以我改了:document.getElementById("inputheurelivraison").selectedIndex

:document.getElementById('inputheurelivraison').options[document.getElementById("inputheurelivraison").selectedIndex].value

在AJAX中发送POST值时,现在它很好。

希望没有人犯同样的错误。

相关文章: