我有一个看起来像这样的多选表单:
<select multiple="multiple" id="id_form-0-project" name="form-0-project">
<option value="0">and another test</option>
<option value="1">another test</option>
<option value="2" selected="selected">one more test</option>
<option value="3">test project</option>
</select>
可以看到,有一个选定值。这始终是我选择的第一个选项。但是,当我使用 shift 单击或命令单击选择多个选项时,不会调整新选择的项目以包含 selected="selected"属性,即使从视觉上看,用户认为所述选择已突出显示。
在这方面它就像一个单一的选择器,但我认为添加“multiple="multiple"属性将允许将选定的属性分配给多个选项。
这是一个常见问题吗?它可能与页面重新加载有关吗?预期的行为是什么?
最佳答案
...the newly selected items are not adjusted so as to contain the selected="selected" attribute...
没错。您还会注意到,当用户更新其值时,input
上的 value
属性不会更新(例如,如果您查看 outerHTML
).
这就是事情的运作方式。这不是错误或您做错了什么。控件的运行时状态不会反射(reflect)在元素的 HTML 属性模型中。
What is the expected behavior?
这是预期的行为。如果您想知道选择了哪些项目,不要查找属性,请查看选项的 selected
property(不是属性)。
如果你想要一个selected HTMLOptionElement
实例的数组:
var selected = Array.prototype.filter.call($("id_form-0-project")[0].options, function(option) {
return option.selected;
});
如果您想要实际值,请将其与 .map
组合:
var selected = Array.prototype.filter.call($("#id_form-0-project")[0].options, function(option) {
return option.selected;
}).map(function(option) {
return option.value;
});
当然,您可以轻松地将其包装到您自己的最小 jQuery 插件中:
jQuery.fn.selectedValues = function() {
if (!this[0] || !this[0].options) {
return undefined;
}
return Array.prototype.filter.call(this[0].options, function(option) {
return option.selected;
}).map(function(option) {
return option.value;
});
};
然后
var values = $("#id_form-0-project").selectedValues();
您的(好)问题突出了 DOM 和 HTML 序列化以及浏览器多年来如何发展的(许多)黑暗 Angular 落之一。没有人会设计这个。 :-) 然而,尽管有些怪癖,但它的效果出奇地好。
关于javascript - html多选表单只能选择一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32771016/