首页 > 解决方案 > 每个 selectedTest 都存在于 data-Test 数组中并获取结果

问题描述

HTML

<div class="col-test" data-test="Swimming pools|Fitness center|Parking|Washer|Spa|Parking|Clubhouse|Valet trash|Washer">

用户从下拉列表中选择了多个选项并获取值

var test = $('#options').val();
console.log(test); // Array [ "Swimming pools", "Fitness center" ]

这是伪代码

for each selectedTest data (from multiselect input)
  check if it exists in the data-test array
    if it does not exists:
              then show = false
    otherwise:
              do nothing and continue to check the next selectedTest (no code is needed here)

下面的代码有问题。我需要确保每个 selectedTest 都存在于 data-Test 数组中。它没有按预期返回结果。代码有问题。

data-test="Swimming pools|Fitness center|Parking|Washer|Spa|Parking|Clubhouse|Valet trash|Washer"

var $variable = $('.col-test');
   if(test && test != null && test.length > 0) {
                console.log($varible.data('test'));
                var arryTest = $varible.data('test').split("|");
                arryTest.forEach((singleTest) => { 
                  if(!test.includes(singleTest)){
                    show = false;
                  }else{
                     //do nothing and continue to check the next selected Amenity
                  }
                });
              }

我可以在控制台中看到一遍又一遍地打印数据测试结果。我认为循环不起作用。

结果

游泳池|健身中心|停车场|洗衣机|水疗中心|停车场|会所|代客垃圾|洗衣机

游泳池|健身中心|停车场|洗衣机|水疗|停车场|会所|代客垃圾|洗衣机|游泳池|健身中心|停车场|洗衣机|水疗|停车场|会所|代客垃圾|洗衣机

游泳池|健身中心|停车场|洗衣机|水疗中心|停车场|会所|代客垃圾|洗衣机|游泳池|健身中心|停车场|洗衣机|水疗|停车场|会所|代客垃圾|洗衣机|游泳池|健身中心|停车场|洗衣机|水疗中心|停车场|会所|代客垃圾|洗衣机

标签: javascriptjquerymulti-select

解决方案


考虑以下示例。

$(function() {
  var dataTest = $("#col-test").val().split("|");
  console.log(dataTest);
  $("#user-options").append("<option>Item 1</option>");
  $.each(dataTest, function() {
    $("#user-options").append("<option>" + this + "</option>");
  });
  $("#user-options").append("<option>Last Item</option>");
  $("#user-options").change(function() {
    var show = true;
    var options = $(this).val();
    console.log("Selected Options", options);
    $.each(options, function(i, o) {
      if (dataTest.indexOf(o) == -1) {
        show = show && false;
      }
    });
    console.log(show);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="col-test" value="Swimming pools|Fitness center|Parking|Washer|Spa|Parking|Clubhouse|Valet trash|Washer" />
<select id="user-options" multiple>
</select>

当用户做出选择时,change会触发一个事件。当有change用户的选择时,将与选项列表进行比较。如果 Option 的索引为-1,则它不存在于列表中,show并将设置为 false。

我没有一套完整的选项,所以我必须根据我拥有的唯一数据构建一个列表,这意味着所有选择的选项都将在列表中,你会得到true. 所以我添加了“第 1 项”和“最后一项”。如果选择其中任何一个,您将获得false.


推荐阅读