2015-04-05 48 views
2

我在WordPress中使用jQuery AJAX加載兩個下拉菜單。我將AJAX數據作爲字符串獲取,我只是將那些<option> s附加到我的<select>字段。它工作正常。但是每次都沒有清除之前的追加。所以它實際上增加了重複選項。jQuery空選擇,但不是第一個選項

所以我做了一個變化,我添加empty()<select>領域:

jQuery.ajax({ 
    type: 'POST', 
    url: ajaxurl, 
    data: {"action": "load_product", 
      "company_id": company_id 
      }, 
    success: function (data) { 
     jQuery('#company-products').empty().append(data); 
    } 
}); 

但我不得不默認情況下選擇欄爲空值的選項,它只是移除一個了。

<select name="product" id="company-products" class="form-control" required> 
    <option value=""><?php _e('Select a product', 'textdomain'); ?></option> 
</select> 

我如何可以附加額外的選項,但不因空(value="")一個空。
請注意,我知道我可以通過jQuery的空字段,但爲了翻譯目的,我無法從那裏通過。所以我想要一個使用jQuery的可靠解決方案,而第一個選項仍然存在。

我甚至試圖將其更改爲:

jQuery('#company-products').not(':first-child').empty(); 
jQuery('#company-products').append(data); 

它不工作,甚至沒有任何附加。 :(

+0

使用[GT](http://api.jquery.com/gt-selector/)選擇。 – 2015-04-05 12:51:44

回答

4

嘗試使用nextAll() - 刪除後的所有元素空<option>

var emptyOp = $('#company-products :first-child'); 

emptyOp.nextAll().remove(); 
emptyOp.after(data); 

Sample Demo

有您可以使用許多其他選擇,

$('#company-products :gt(0)').remove(); 
$('#company-products').append(data); 

OR

$('#company-products :not(:first-child)').remove(); 
$('#company-products').append(data); 
0

如果你只是嘗試寫

<?php _e('Select a product', 'textdomain'); ?> 

JS變量,並通過你的選擇,因爲你寫的,從jQuery的

var selectOption = '<?php _e('Select a product', 'textdomain'); ?>'; 
+0

好的嘗試!但它顯示了一切,但以某種方式不顯示文本:http://prntscr.com/6ptvtb – 2015-04-05 12:54:33

+0

喲需要在你的JS代碼之前寫在你的PHP代碼。 – 2015-04-05 13:14:02

1

不要使用empty()只是使用remove()

$('#company-products').children('option:not(:first)').remove(); 

希望這能對你的作品

相關問題