Jeff Beagley
Jeff Beagley

Reputation: 1025

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]);
    }
});

Upvotes: 1

Views: 629

Answers (2)

dsgriffin
dsgriffin

Reputation: 68626

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

Upvotes: 1

TRGWII
TRGWII

Reputation: 648

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

Upvotes: 0

Related Questions