猿问

在选择框中获取重复值,需要从选择框中删除重复选项

我想首先从 php 中取消选择的值中删除重复值,还是可以在 jquery/javascript 中?


我正在我的网站上的编辑页面上工作,我需要在其中显示一个SELECT框,其中一些值应该被选择,而一些不应该被选中。


从数据库中获取数据后,我有以下代码


<select name="tour_category[]" multiple="multiple" style="height:300px;">

  <option value="1" selected>Family</option>

  <option value="3" selected>Wildlife</option>

  <option value="4" selected>Cuisine (Food Tours & Food Walks)</option>

  <option value="1">Family</option>

  <option value="1">Family</option>

  <option value="2">Religion & Spirituality</option>

  <option value="2">Religion & Spirituality</option>

  <option value="2">Religion & Spirituality</option>

  <option value="3">Wildlife</option>

  <option value="3">Wildlife</option>

  <option value="4">Cuisine (Food Tours & Food Walks)</option>

  <option value="4">Cuisine (Food Tours & Food Walks)</option>

  <option value="5">Boat Trips</option>

  <option value="5">Boat Trips</option>

  <option value="5">Boat Trips</option>

  <option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions)</option>

  <option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions)</option>

  <option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions)</option>

  <option value="7">Weekend Gateways</option>

  <option value="7">Weekend Gateways</option>

  <option value="7">Weekend Gateways</option>                      </select>


但我需要显示以下输出:


<select name="tour_category[]" multiple="multiple" style="height:200px;">

  <option value="1" selected>Family</option>

  <option value="2" selected>Religion & Spirituality</option>

  <option value="3" selected>Wildlife</option>

  <option value="4">Cuisine (Food Tours & Food Walks)</option>

  <option value="5">Boat Trips</option>

  <option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions</option>

  <option value="7">Weekend Gateways</option>

</select>


12345678_0001
浏览 128回答 2
2回答

慕虎7371278

如果您想实现这一点,我建议您option使用 for 循环或映射显示标签,并从要映射的数组中删除重复项。您可以通过使用 ES6 来实现这一点Set。所以假设你有以下代码:const array = ['Family', 'Family', 'Wildelife', 'Wildlife'];const uniqueSet= new Set(array);const uniqueArray = [...uniqueSet];//the new array will be ['Family', 'Wildlife']

精慕HU

在选择标签中添加一个属性 id="tour_category" 并尝试$(document).ready( function(){&nbsp; &nbsp; var a = new Array();&nbsp; &nbsp; $("#tour_category").children("option").each(function(x){&nbsp; &nbsp; &nbsp; &nbsp; test = false;&nbsp; &nbsp; &nbsp; &nbsp; b = a[x] = $(this).val();&nbsp; &nbsp; &nbsp; &nbsp; for (i=0;i<a.length-1;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (b ==a[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;test =true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (test) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$(this).remove();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })});
随时随地看视频慕课网APP
我要回答