如何使用JavaScript设置多项选择的值 [英] How to set values of multiple select using JavaScript

查看:102
本文介绍了如何使用JavaScript设置多项选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

To set data of an <input> element using JavaScript, we assign the value and name of that element like this:

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

在具有multiple属性的<select>情况下,如何设置该选择元素的值?例如,如何设置下面的myselect元素的值:

In the case of a <select> where the multiple attribute is present, how do I set the value of that select element? For instance, how would I set the value of the myselect element below:

<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".

I tried to set the value by doing this myselect.value=[1,2] however it does not work. After selecting option1 and option2 I expected that it returns [1,2], but it just returns "1".

推荐答案

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

To programmatically set multiple value options on a multi-select, you need to manually add selected attributes to the <option> elements that you want to select.

一种解决方法如下:

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>

这篇关于如何使用JavaScript设置多项选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆