如何使用JavaScript设置多个选择的值

问题描述 投票:1回答:3

要使用JavaScript设置<input>元素的数据,我们分配该元素的值和名称,如下所示:

var form = document.createElement("form");
var element = document.createElement("input"); 
element.value=value;
element.name=name;

对于存在<select>属性的multiple,如何设置该select元素的值?例如,我如何设置下面的myselect元素的值:

<form method="post" action="/post/" name="myform">
  <select multiple name="myselect" id="myselect">
    <option value="1">option1</option>
    <option value="2">option2</option>
        ...

我尝试通过这个myselect.value=[1,2]设置值,但它不起作用。选择option1option2后,我预计它会返回[1,2],但它只返回“1”。

javascript html html-select
3个回答
0
投票

要以编程方式在多选中设置多个值选项,您需要手动将selected属性添加到要选择的<option>元素。

一种方法如下:

const select = document.getElementById('myselect')
const selectValues = [1, 2];

/* Iterate options of select element */
for (const option of document.querySelectorAll('#myselect option')) {

  /* Parse value to integer */
  const value = Number.parseInt(option.value);

  /* If option value contained in values, set selected attribute */
  if (selectValues.indexOf(value) !== -1) {
    option.setAttribute('selected', 'selected');
  }
  /* Otherwise ensure no selected attribute on option */
  else {
    option.removeAttribute('selected');
  }
}
<select multiple name="myselect" id="myselect">
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
  <option value="4">option4</option>
</select>


1
投票

有用

var element = document.getElementById('selectMultiple');

// Set Values
var values = ["Gold", "Bronze"];
for (var i = 0; i < element.options.length; i++) {
    element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}

// Get Value
var selectedItens = Array.from(element.selectedOptions)
        .map(option => option.value)


spanSelectedItens.innerHTML = selectedItens
<select name='selectMultiple' id="selectMultiple" multiple>
    <option value="Gold">Gold</option>
    <option value="Silver">Silver</option>
    <option value="Bronze">Bronze</option>
</select>
<br />
Selected: <span id="spanSelectedItens"></span>

0
投票

您可以通过options对象的select属性访问选择选项的数组。每个选项都有一个你可以设置的selected属性。

document.myform.myselect.options[0].selected = true;

您可以使用查询选择器按值访问选项:

document.myform.myselect.querySelector("option[value="+value+"]")[0].selected = true;
© www.soinside.com 2019 - 2024. All rights reserved.