简体   繁体   English

带有多个值的jQuery Multi-Select

[英]JQuery Multi-Select with multiple values

I have a form where you select a location, this location has a zip code tied to it and is captured in the data-foo value. 我有一个表单,您可以在其中选择一个位置,该位置具有邮政编码,并在data-foo值中捕获。 What I need is an array built upon multiple locations being selected. 我需要的是一个基于多个位置选择的数组。

An example would be if both would be selected I'd have 65807 => 71118 一个例子是,如果两个都被选中,我将有65807 => 71118

Form: 形成:

 <form enctype='multipart/form-data' role='form' action='' method='post'> <div class="row"> <div class="col-md-3"> <div class='form-group'> <label for='select'>Destination(s)&nbsp;</label> <select name='destination[]' style='height: 200px;' multiple class='form-control' multiple='multiple' id='destination' style='lane'>"; <option value='Springfield' data-foo='65807'>Springfield, MO</option> <option value='Shreveport' data-foo='71118'>Shreveport, LA</option> </select> </div> </div> </div> </form> 

What I have so far for JS: 到目前为止,我对JS有什么:

 $(function(){ $('#origin').change(function(){ var selected = $(this).find('option:selected'); $('#origin_zip').html(selected.data('foo')); }).change(); }); $('#destination').change(function() { $('#destination_zip').text(''); var selected = $('#destination').val(); for (var i = 0; i < selected.data; i++) { $('#destination_zip').data($('#destination_zip').data('data-foo') + selected[i]); } }); 

EDIT: 编辑:

This is the code that works on building the array with the text, but not the data-foo that I need. 这是使用文本构建数组的代码,而不是我需要的data-foo。

 $('#destination').change(function() { $('#destination_zip').text(''); var selected = $('#destination').val(); for (var i = 0; i < selected.length; i++) { $('#destination_zip').text($('#destination_zip').text() + selected[i]); } }); 

The following could be used: 可以使用以下内容:

$('#destination').change(function() { // Whenever the select is changed
    var arr = []; // Create an array
    $('#destination option:selected').each(function(){ // For each selected location
        arr.push($(this).data("foo")); // Push its ZIP to the array
    });
    console.log(arr); // will include the ZIP code(s) of selected location(s).
});

jsFiddle example here jsFiddle示例在这里

Something like this? 像这样吗 (kind of ugly, I know) (有点丑,我知道)

$('#destination').change(function() {
  var selected = [];
  for(i = 0; i < $('#destination').children().length; i++){
    selected[i] = $($('#destination').children()[i]).data('foo');
  }
  console.log(selected);
});

Edit: nevermind, look at @dsg's answer 编辑:没关系,看看@dsg的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM