2011-12-09 231 views
2

我正在研究一個在模態對話框中彈出的多選。當對話框關閉時,我正在填充<ul><li>,其中包含來自:selected選項的文本。當單擊各個<li>時,我希望<li>消失,並且相應的:selected<option>變爲未選中狀態。除了取消選擇<option>之外,我有所有工作。jQuery - 刪除選擇選項:點擊選中的屬性

這裏是我的代碼:

$('.control-finished').click(function(){ 
      $('ul.multiselect-dropdown-options-'+name+'').empty(); 
      $('option:selected', select).each(function(index, value) { 
       var livalue = $(this).attr('value'); 
       $('ul.multiselect-dropdown-options-'+name+'').append('<li class="dropdown-option '+livalue+'">'+$(value).text()+'<!-- <a class="remove-option '+livalue+'"> -->x</li>'); 
       $('li.dropdown-option').click(function(){ 
        $(this).fadeOut(500, function() { $(this).remove(); }); 
        $('option:selected', this).removeAttr('selected'); 
       }); 
      });   

     }); 

任何幫助,不勝感激!

+0

你能發佈你的HTML嗎? – Purag

+0

我認爲你不能刪除:選中的狀態。或者你可以,但是這個項目仍然會在選擇框中被直觀地選中。也許你可以選擇不同的選項(即第一個)? –

+0

哇,有很多古怪處理列表框。總之,看看我的帖子。使用.prop('selected','')原來是最好的選擇。 – rkw

回答

5

我相信你的問題是在這條線:

$('option:selected', this).removeAttr('selected'); 

這是說,找到所有選項:選擇的是li.dropdown選項的後代。但是你在淡出後刪除這些,所以當然不會找到它。

所以你需要在上面的jQuery函數中改變第二個參數。 (this),到你想要搜索的實際父dom元素。

我不知道你的HTML是什麼樣的,所以我不能爲你提供更詳細的解決方案。

+0

感謝您的幫助! – Zumwalt

1
$('option:selected').attr('selected', ''); 

或單選框

$('#selectboxID').attr('selected', '-1'); 

但話又說回來,你實際上結合你的每個函數中點擊功能,並試圖消除內部有一個「這個」範圍上選擇框選定值在你已經在同一個'this'範圍內使用remove()之後?

0

試試這個:http://jsfiddle.net/rkw79/mmBKf/3/

$('select').change(function() { 
    $('ul').empty(); 

    $('option:selected').each(function() { 
     $('<li></li>').text($(this).val()).appendTo($('ul')); 
    }); 
}); 

$('ul').on('click', 'li', function() { 
    $('option[value="' + $(this).text() + '"]').prop('selected',''); 
    $(this).remove(); 
}); 
0

我有同樣的問題 我試圖

removeAttr('selected'); 

removeProp('selected'); 

prop('selected',false); 

通過

$('#selectboxID').val(newVal); 

改變選擇框的值...

但還是選定的屬性,甚至具有空值 存在我終於做了以下刪除它

$('#selectboxID').html($('#selectboxID').html().replace('selected','')); 
0

你可以用這個試試。希望這可以幫助你。

var $element = $("#DropDownList1"); 
    $element.change(function() { 
     $element.find('option').removeAttr('selected') 
     .filter("[value=" + this.value + "]") 
     .attr("selected", "selected"); 
     console.log(this.value); 
    }); 

歡呼聲。