使用JavaScript获取数据列表选项值的选定值 [英] Get selected value of datalist option value using javascript

查看:85
本文介绍了使用JavaScript获取数据列表选项值的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Javascript将HTML5 DataList中的某些值添加到<select multiple>控件中.但是我不知道该怎么做.

I need to add some values from a HTML5 DataList to a <select multiple> control just with Javascript. But I can't guess how to do it.

这是我尝试过的:

<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
  <option label="Red" value="1">
  <option label="Yellow" value="2">
  <option label="Green" value="3">
  <option label="Blue" value="4">
</datalist>

<button type="button" onclick="AddValue(document.getElementById('AllColors').value, document.getElementById('AllColors').text);">Add</button>
<select id="Colors" size="3" multiple></select>

function AddValue(Value, Text){

//Value and Text are empty!

var option=document.createElement("option");
option.value=Value;
option.text=Text;

document.getElementById('Colors').appendChild(option);

}

推荐答案

这应该有效.我已经将值选择逻辑移到了方法本身中. 您只会从输入中获取值.您将需要使用该值从数据列表中选择标签.

This should work. I have moved the value selection logic into the method itself. You will only get the value from the input. You will need to use the value to select the label from the datalist.

function AddValue(){
  const Value = document.querySelector('#SelectColor').value;

  if(!Value) return;

  const Text = document.querySelector('option[value="' + Value + '"]').label;

  const option=document.createElement("option");
  option.value=Value;
  option.text=Text;

  document.getElementById('Colors').appendChild(option);
}

这是工作示例.

这篇关于使用JavaScript获取数据列表选项值的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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