2015-02-06 126 views
1

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

一个例子是,如果既会选择我有65807 => 71118

形式:

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

编辑:

这是用于构建数组与文本,但不是我需要的数据-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]); 
 
    } 
 
});

+0

所以,你希望用户能够选择多个地点?选择选项菜单只允许选择一个选项。我想你想要复选框或单选按钮。你给的例子是一个在javascript中不可用的关键值。你可以通过这种方式构建一个json对象。 – floor 2015-02-06 22:48:24

+0

我可以让它基于.text使用.val()已经建立一个数组..我只需要将.text更改为.data的形式 – 2015-02-06 22:50:45

+0

不知道你想在这里做什么...有什么区别.text和.data之间? – TRGWII 2015-02-06 22:52:38

回答

1

下可以使用:

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

+0

作品完美,谢谢dsg! – 2015-02-08 08:06:02

0

像这样的事情? (有点丑,我知道)

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

编辑:没关系,看看@ DSG的回答