分离数组的值以选择框

时间:2018-03-01 16:00:13

标签: jquery arrays

我有一个不同大小的数组,我想将每行大小分成自己的下拉列表。

我无法将每个尺寸分隔为自己的选择选项。

var arraySize = [
                 "S, M, L", 
                 "XS, S, M, L"
                ];

$.each(arraySize, function(index, element) {
    $('.sizeContainer').append($('<option>', {text: element}));
});


// Desired output
<select>
  <option value="S">S</option>
  <option value="M">M</option>
  <option value="L">L</option>
</select>

<select>
  <option value="XS">XS</option>
  <option value="S">S</option>
  <option value="M">M</option>
  <option value="L">L</option>
</select>

https://jsfiddle.net/jdzax0rg/8/

2 个答案:

答案 0 :(得分:0)

首先,您需要在每次迭代中添加<select>,然后用逗号分隔“元素”以获取不同的大小,并将每个大小添加到前面的下拉列表中。

一种解决方案是:

$('#testButton').click(function() {

  var arraySize = ["S, M, L", "XS, S, M, L"];

  $.each(arraySize, function(index, element) {
  
    // Create the drop down list and keep a reference
    var ddl = $("<select>").appendTo(".sizeContainer");

    // Split the sizes by comma
    var sizes = element.split(",");
    
    // Loop through each size adding it to the ddl
    for (var i in sizes) {
      ddl.append($('<option>', {
        text: sizes[i],
        value: sizes[i]
      }));
    }
  });

  return false;

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="testButton" href="#">Test</a>
<form method="POST" class="sizeContainer">
</form>

更新了小提琴:https://jsfiddle.net/jdzax0rg/14/

答案 1 :(得分:0)

使用以下内容。看到它正常工作here

<!-- HTML -->
<a id="testButton" href="#">Test</a>
  <form method="POST">
    <select class="sizeContainer">

    </select>
  </form>

<!-- JS  -->
$('#testButton').click(function(){

    var arraySize = ["S, M, L", "XS, S, M, L"];

    $.each(arraySize, function(index, element1) {
            var res = element1.split(",");
        $.each(res, function(index, element) {
        $('.sizeContainer').append($('<option>', {text: element}));
        });
    });

  });