javascript - 具有多个值的 JQuery 多选

标签 javascript jquery html multi-select

我有一个表单,您可以在其中选择一个位置,该位置有一个与其绑定(bind)的邮政编码,并在 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 example here

关于javascript - 具有多个值的 JQuery 多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376075/

相关文章:

javascript - 图像元素 'clear' 背景颜色不起作用

html - 试图让一个 div w/100% 高度和溢出自动在 Firefox 中工作

javascript - 如何在JQuery中使用带有 'for'的多个数组元素

html - Apple iphone 导致按钮在网站上被压扁

javascript - 如何通过动画CSS隐藏点击的div

javascript - 使用 JavaScript/JQuery 的 HTML 页面中的热键功能

javascript - ckeditor - javascript拼写检查插件

JAvascript 180 到 -180 旋转

javascript - 如何获取我网站中的国家/地区列表

javascript - 调用 Jquery 对话框并传递消息字符串