<选择>标记并向javascript方法返回多个值 [英] <select> tag and returning multiple values to javascript method

查看:56
本文介绍了<选择>标记并向javascript方法返回多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对从下拉菜单发送的数据有问题,即使选择了多个值,选择器也只返回一个值.我已经在网上搜索了解决方案,但是它们都使用PHP,JQuery或我所学课程范围之外的某些方法.捕获多个选定的项目.我已经尝试了单个选项的.value,但是它返回了所有选项,而不仅仅是返回了所选择的选项.发送多个值是否有某种技巧?

I have an issue with the data which is sent from a drop down menu, the selector only returns a single value, even when multiple values are selected. I have searched online for a solution to this, but they all use PHP, JQuery or some method outside the scope of the course I am taking; to capture multiple selected items. I have tried .value of the individual options, but that returns all of the options rather than just the ones which are selected. Is there some kind of trick to sending multiple values?

这是我的菜单代码.例如,如果我选择"JAVA编程",网络"和视频游戏",则仅发送"JAVA编程".

Here is my code for the menu. For example If I select JAVA PROGRAMMING, NETWORKS and VIDEO GAMES, only JAVA PROGRAMMING is sent.

<select multiple id="CK_Expertise">
  <option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
  <option  id="CK_Exp2" value="Networks">NETWORKS</option>
  <option  id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
  <option  id="CK_Exp4" value="Accounter">ACCOUNTER</option>
  <option  id="CK_Exp5"  value="Help Desk">HELPDESK</option>
  <option  id="CK_Exp6"  value="C++ programming">C++</option>
  <option  id="CK_Exp7"  value="Programming">PROGRAMMING</option>
</select>

我也尝试过在DOM中使用选择对象, http://www.w3schools.com/jsref/dom_obj_select.asp 其中有几种方法可以访问下拉菜单中的选项.我正在寻找一个特别是名为selectedIndex的方法,但是它仅返回第一个选定选项的索引,而不是所有选定选项的索引.
仅使用Javascript和DOM,有没有简单的解决方案?

I have also tried using the Select Object in the DOM, http://www.w3schools.com/jsref/dom_obj_select.asp which has a few methods for accessing the options in the dropdown menu. One method in particular called selectedIndex, seemed to be what I am looking for, however it only returns the the index of the first selected option, instead of all of the selected options.
Is there a simple solution to this using just Javascript and the DOM?

谢谢-克里斯

推荐答案

获取选项,迭代并检查是否已选择它们,然后将值添加到数组中

Get the options, iterate and check if they are selected, and add the values to an array

var select = document.getElementById('CK_Expertise'),
   options = select.getElementsByTagName('option'),
   values  = [];

    for (var i=options.length; i--;) {
        if (options[i].selected) values.push(options[i].value)
    }

    console.log(values)

FIDDLE

或更花哨

var select = document.getElementById('CK_Expertise'),
    values = Array.prototype.filter.call(select.options, function(el) {
        return el.selected;
    }).map(function(el) {
        return el.value;
    });

    console.log(values)

FIDDLE

这篇关于&lt;选择&gt;标记并向javascript方法返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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