2016-07-25 53 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」或其他選項。 –

相關問題