繁体   English   中英

带有多个值的jQuery Multi-Select

[英]JQuery Multi-Select with multiple values

我有一个表单,您可以在其中选择一个位置,该位置具有邮政编码,并在data-foo值中捕获。 我需要的是一个基于多个位置选择的数组。

一个例子是,如果两个都被选中,我将有65807 => 71118

形成:

 <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> 

到目前为止,我对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]); } }); 

编辑:

这是使用文本构建数组的代码,而不是我需要的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]); } }); 

可以使用以下内容:

$('#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示例在这里

像这样吗 (有点丑,我知道)

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

编辑:没关系,看看@dsg的答案

暂无
暂无

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

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