无法提交带有<选择多个必填项>在Internet Explorer中

Cannot submit form with <select multiple required> in Internet Explorer

本文关键字:gt Explorer Internet 提交 lt 选择      更新时间:2024-01-22

首次提交时,<选择>被选中,导致HTML5验证失败,从而完全阻止提交。

然而,如果我们通过JavaScript选择一个选项,那么在随后的提交中提交仍然失败。

如果手动选择已选择选项以外的选项(或者取消选择并重新选择),则会成功。

Bug或功能?它是已知的行为还是在某个地方记录的?我找不到任何推荐人。

var done = false;
$(document).ready(function() {
  $("#s").on("click", function() {
    if (done) {
      return;
    }
    // run once
    done = true;
    setTimeout(function() {
      $("#a").prop("selected", true);
      console.log($("#x").val());
    }, 100); // delay to prevent submission with set option
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
  <select id="x" name="x" required="required" multiple="multiple">
    <option value="a" id="a">Anton</option>
    <option value="b">Berta</option>
  </select>
  <input id="s" type="submit" name="btn" value="Submit" />
</form>

这似乎与在<option>上设置.prop有关。

当您在select输入上设置selectedIndex时,一切正常。检查更新的小提琴:

document.getElementById('btn-select').addEventListener('click', function() {
    var select = $("#x")[0];
    // select the first one
    // select.selectedIndex = 0;
    // or loop through options and select based on a condition
    for (var i = 0; i < select.options.length; i++) {
        if (select.options[i].value === 'b') {
            select.selectedIndex = i;
            return;
        }
    }
})

https://jsfiddle.net/5hbey7en/8/

所以你的例子会变成:

var done = false;
$(document).ready(function() {
  $("#s").on("click", function() {
    if (done) {
      return;
    }
    // run once
    done = true;
    setTimeout(function() {
      $("#x")[0].selectedIndex = 0;
      console.log($("#x").val());
    }, 100); // delay to prevent submission with set option
  });
});