2016-07-25 128 views
0

我使用AJAX和PHP获取包含教育数据的对象数组。最多可以显示4个不同的<select></select>标签。我怎样才能为每个选择设置正确的选项并删除重复?如何为相同名称的选择设置选定的选项?

我想这一点,这会导致重复:

<div class="col-md-3"> 
    <label>Levels</label> 
    <div class="form-group form-group-custom"> 
     <select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]"> 
      <option value="' +data.degree_name + '">' + data.degree_name + '</option> 
      <option value="A">A</option> 
      <option value="B">B</option> 
      <option value="C">C</option> 
     </select> 
    </div> 

然后我试图删除与JS,这仅与第一选择标记工作重复:

var usedDegrees = {}; 
    $("select[name='userEducationDegree[]'] > option").each(function() { 
     console.log("removing"); 
     if(usedDegrees[this.text]) { 
      $(this).remove(); 
     } else { 
      usedDegrees[this.text] = this.value; 
     } 
    }); 

电流输出我有什么用上面的设置是:

 <option value="A">A</option> 
     <option value="A">A</option> 
     <option value="B">B</option> 
     <option value="C">C</option> 

我想要的是<option value="A">A</option>被删除或<option>被选中。

+1

你如何识别重复?样本输入在哪里?什么是预期的输出?实际产出是多少? – RobG

+0

@RobG检查编辑请求 – raqulka

回答

0

根据您的要求

我想的是A的一个是 删除或选定。

我们可以选择的选项,因为每度名称。为此,你可以试试这个代码

HTML:

<div class="col-md-3"> 
    <label>Levels</label> 
    <div class="form-group form-group-custom"> 
     <select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]"> 
      <option value="Select">Select</option> 
      <option value="A">A</option> 
      <option value="B">B</option> 
      <option value="C">C</option> 
     </select> 
    </div> 
     </div> 

js代码会像

//让degree_name = 'B';

var degree_name='B'; 
     $("select[name='userEducationDegree[]'] option").each(function() { 

      if(degree_name===this.value) { 
       this.selected=true; 
      } 
     }); 

希望它能为你工作。

0

你不需要选择像你这样修正后的值。重复选项来自您的选择,这不是必需的。

只需使用下面的线会自动选择value比赛字符串。

jQuery的

$("select[id^='userEducationDegree']").val('A'); 

// in your case it should be data.degree_name instead of 'A' 

这里是片段

$(function(){ 
 
    $("select[id^='userEducationDegree']").val('A'); 
 
    $("#sel").html('`'+$("select[id^='userEducationDegree']").val()+'`'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]"> 
 
      <option value="-1">--Select--</option> 
 
      <option value="A">A</option> 
 
      <option value="B">B</option> 
 
      <option value="C">C</option> 
 
</select> 
 
<p>See <strong id="sel"></strong> is selected</p>

+0

但是,如果值是B,该怎么办? – raqulka

+0

用'data.degree_name'替代'val('A')'中的'A',然后它会自动检测出什么要选择何种“B”或“C”或其他选项。 –

相关问题