【问题标题】:JQuery Multi-Select with multiple values具有多个值的 JQuery 多选
【发布时间】:2015-02-06 22:40:57
【问题描述】:

我有一个表单,您可以在其中选择一个位置,这个位置有一个与之相关的邮政编码,并被捕获在 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]);
    }
});

【问题讨论】:

  • 那么您希望用户能够选择多个位置吗?选择选项菜单只允许选择一个选项。我认为您需要复选框或单选按钮。您提供的示例采用 javascript 中不可用的键值形式。你可以用这种方式构建一个 json 对象。
  • 我可以让它基于 .text 使用 .val() 构建一个数组。我只需要将 .text 更改为 .data 的形式
  • 不确定你想在这里做什么... .text 和 .data 有什么区别?
  • 我已使用仅适用于文本的代码更新了原始帖子。
  • 到 TRGWII - 我需要提取保存在 data-foo 中的邮政编码,但让用户选择 City, St.

标签: javascript jquery html multi-select


【解决方案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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2011-11-30
      相关资源
      最近更新 更多