简体   繁体   中英

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

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:

 $(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.

 $('#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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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