如何在javascript中访问多个选择数组数据 [英] how to access multiple select array data in javascript

查看:17
本文介绍了如何在javascript中访问多个选择数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多选框,我想在 javascript 中访问选定的数据.代码如下:

I have a multiple select box and I want to access the selected data in javascript. Here is the code:

<form onsubmit="return false;" id="multisel">
  <select name="a[]" id="a" multiple style="width:350px;" tabindex="4">
    <option value="Pedro">1</option>
    <option value="Alexis">2</option>
    <option value="Messi">3</option>
    <option value="Villa">4</option>
    <option value="Andres">5</option>
    <option value="Sergio">6</option>
    <option value="Xavi">7</option>
  </select>

  <button id="btn1" onclick="ajaxmultiselect()" type="submit" class="btn btn-primary">Save changes</button>

  <p id="status"></p>
</form>

这是我迄今为止尝试过的代码:

Here is the code I have tried so far :

<script>    
function ajaxmultiselect(){
  var input  = [];
  input = document.getElementById("a").value;
  var status = _("status");
  if(input == ""){
    status.innerHTML = "Fill out all of the form data";
  }else {
    status.innerHTML = input;
  }
}
</script>

当我运行代码时,它只给出第一个值.我试图访问 php 中的值,它工作正常,它在 php 中将值作为数组传递.为什么它不能用 javascript 做同样的事情?

When I run the code it only gives the first value. I tried to access the values in php and it works fine, it passes the value as an array in php. Why isn't it doing the same with javascript?

我还尝试为值的长度运行一个循环,但这仅计算第一个选择的长度.我想显示所有将被选中的值.

I also tried to run a loop for the length of the value but that calculates the length of the first selection only. I want to display all the values that will be selected.

任何帮助将不胜感激.

推荐答案

您可以执行以下操作:

function getSelectedOptions(element) {
    // validate element
    if(!element || !element.options)
        return []; //or null?

    // return HTML5 implementation of selectedOptions instead.
    if (element.selectedOptions)
        return element.selectedOptions;

    // you are here because your browser doesn't have the HTML5 selectedOptions
    var opts = element.options;
    var selectedOptions = [];
    for(var i = 0; i < opts.length; i++) {
         if(opts[i].selected) {
             selectedOptions.push(opts[i]);
         }
    }
    return selectedOptions;
}

然后改变你的ajaxmultiselect(),这样你就可以这样称呼它:

and then change your ajaxmultiselect() so you call it like this:

input = getSelectedOptions(document.getElementById("a"));

您将不得不迭代这些值.

You will have to iterate for the values tho.

这篇关于如何在javascript中访问多个选择数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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