Javascript 如何让html选择以使用javascript显示选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11023171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:04:37  来源:igfitidea点击:

how to get html select to show selected value with javascript

javascripthtmlhtml-select

提问by windforceus

I have a select dropdownlist with 1 item selected at page load in html.

我有一个选择下拉列表,其中在 html 页面加载时选择了 1 个项目。

<select name = "options">
  <option value = "1">Item1</option>
  <option value = "2" selected>Item2</option>
  <option value = "3">Item3</option>
  <option value = "4">Item4</option>
</select>

Now I want to capture new select option when user press shift and select another option such as "Item 3".

现在我想在用户按下 shift 并选择另一个选项(例如“项目 3”)时捕获新的选择选项。

I have the following code to find all the selections in the list

我有以下代码来查找列表中的所有选择

 var value = "";
 for (var intLoop = 0; intLoop < Form.elements[index].length; intLoop++) {

     if(Form.elements[index][intLoop].selected )
             value = value + Form.elements[index][intLoop].value;
 }

I can see the "Item 2" and "Item 3" are selected but i want to get capture "Item 3" only. Is it possible?

我可以看到选择了“项目 2”和“项目 3”,但我只想捕获“项目 3”。是否可以?

回答by Juan Mendes

Here's code that will tell you what has been selected and what has been deselected http://jsfiddle.net/8dWzB/

这里的代码会告诉你什么被选中,什么被取消了http://jsfiddle.net/8dWzB/

It uses Array.prototype.indexOf, and it's not the fastest way to do it. But it should get you going in the right direction.

它使用Array.prototype.indexOf,这不是最快的方法。但它应该让你朝着正确的方向前进。

HTML

HTML

<select id="options" multiple="multiple">
  <option value = "1">Item1</option>
  <option value = "2" selected>Item2</option>
  <option value = "3">Item3</option>
  <option value = "4">Item4</option>
</select>

JS

JS

function getSelectedIndexes(select) {
   var selected = [];
   for (var i = 0; i  < select.options.length; i++) {
       if(select.options[i].selected ) {
            selected.push(i);
       }
   }
   return selected;
}

var select = document.getElementById("options");
var prevSelected = getSelectedIndexes(select);

select.onchange = function(e) {
    var currentlySelected = getSelectedIndexes(this);

    for (var i =0; i < currentlySelected.length; i++) {
        if (prevSelected.indexOf(currentlySelected[i]) == -1) {
            console.log("Added to selection ", this.options[currentlySelected[i]].text);
        }
    }

    for (var i =0; i < prevSelected.length; i++) {
        if (currentlySelected.indexOf(prevSelected[i]) == -1) {
            console.log("Removed from selection  ", this.options[prevSelected[i]].text);
        }
    }        
    prevSelected = currentlySelected;
};
?

If you really only want to know which item was last clicked, you can use the following code. I'll use jQuery so I can easily set a handler on all the option objects. Remember this won't work if you change the selection with the keyboard

如果你真的只想知道最后点击的是哪个项目,你可以使用下面的代码。我将使用 jQuery,因此我可以轻松地在所有选项对象上设置处理程序。请记住,如果您使用键盘更改选择,这将不起作用

    $('option').click(function(e){
        var parentNode = this.parentNode;
        for (var i=0; i < this.parentNode.options.length; i++) {
            if (parentNode.options[i] == this) {
              console.log('Clicked item with index', i);
              break;
            }
        }
    });

回答by Jonathan Nicol

You could check the value of the selected options before a change event (e.g. item 1 and 2 are selected) and then again after the event (e.g. item 1, 2 and 3 are selected), and compare the difference.

您可以在更改事件之前(例如选择第 1 项和第 2 项),然后在事件之后(例如选择第 1、2 和 3 项)再次检查所选选项的值,并比较差异。

Here is an example.

这是一个例子。

Fiddle here: http://jsfiddle.net/FnAuz/4/

在这里小提琴:http: //jsfiddle.net/FnAuz/4/

I modified your selectto allow multiple selections since I take it that's the crux of the problem.

我修改了您select以允许多项选择,因为我认为这是问题的关键。

HTML:

HTML:

<form id="my-form">
    <select name = "options" id="options" multiple>
      <option value = "val1">Item1</option>
      <option value = "val2">Item2</option>
      <option value = "val3">Item3</option>
      <option value = "val4">Item4</option>
    </select>
</form>?

JS:

JS:

var oldValue = "";
document.getElementById('options').onchange = function() {
    var myForm = document.getElementById ('my-form');
    var value = "";
    for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
        if(myForm.elements[0][intLoop].selected) {
            value = value + myForm.elements[0][intLoop].value;
        }
    }
    for (var intLoop = 0; intLoop < myForm.elements[0].length; intLoop++) {
        var optionVal = myForm.elements[0][intLoop].value;
        if(myForm.elements[0][intLoop].selected && value.indexOf(optionVal) !== -1  && oldValue.indexOf(optionVal) === -1) {
            console.log('Last clicked was ' + myForm.elements[0][intLoop].value)
        }
    }
    oldValue = value;
};

EDIT:I just noticed that my example works when the user makes command/ctrl selections, but if they make a shift selection then ALL the new values will be counted as the 'last clicked item'. So my code would need some work to account for this scenario. I'm out of time, but hopefully my code is useful in its current state nevertheless!

编辑:我刚刚注意到我的示例在用户进行命令/ctrl 选择时起作用,但是如果他们进行了移位选择,那么所有新值都将被计为“最后点击的项目”。所以我的代码需要一些工作来解决这种情况。我没时间了,但希望我的代码在当前状态下仍然有用!

回答by alfasin

It started looking messy so I'm posting it as an answer:

它开始看起来很乱,所以我将其发布为答案:

<html>
<head>
<script type="text/javascript">
<!--
var value = '0';

document.getElementById('options').onchange = function() {
    value = parseInt(value) + parseInt(this.value);
    alert(value);
}
-->
</script>
</head>
<body>
    <select name="options" id="options">
    <option value = "1">Item1</option>
      <option value = "2" selected>Item2</option>
      <option value = "4">Item3</option>
      <option value = "8">Item4</option>
    </select>
</body>    
</html>

Edition for selecting multiple items: well, if you want to accumulate items you can assign binary IDs to each product and then you can extract all the selected products from the total. for example, if the total is: 7 you can easily translate it to a binary string "111" which means they selected items 1,2,4. Sounds a bit crazy, I know, just an idea ;)

选择多个项目的版本:好吧,如果您想累积项目,您可以为每个产品分配二进制 ID,然后您可以从总数中提取所有选定的产品。例如,如果总数为:7,您可以轻松将其转换为二进制字符串“111”,这意味着他们选择了项目 1、2、4。听起来有点疯狂,我知道,只是一个想法 ;)

回答by tilak

Try this :

尝试这个 :

var e = document.getElementById("ID_of_Select_Element");
var _selectedValue= e.options[e.selectedIndex].value;