2014-09-05 32 views
0

我有一個選擇選項,如果我選擇任何相關的選項相關的div顯示。高興這很好。但我想要做出類似於如果我選擇它將顯示相關的div但選擇它自己將被刪除的選項。 FIDDLE刪除執行操作後的選擇選項

這可能嗎?任何幫助將不勝感激。

JS

$(document).ready(function() { 
    $('#contact-location').change(function(){ 
     var location = $(this).val(), 
     div = $('#' + location); 

     $('div').hide(); 
      div.show(); 

    }); 
}); 
+0

對不起,我的英語不好。你的例子不匹配。我想在顯示相關的div後刪除該選項:) – Raihan 2014-09-05 20:11:32

+0

你的意思是完全從列表中刪除它? – 2014-09-05 20:11:49

+0

是的想要類似的東西 – Raihan 2014-09-05 20:12:28

回答

1

固定我的答案,以反映問題的更新:

$(document).ready(function() { 
    $('#contact-location').change(function(){ 
     var location = $(this).val(), 
     div = $('#' + location); 
     var selIndex = $("#contact-location").prop('selectedIndex'); 
     $("#contact-location").prop(selIndex).remove(); 
     $('div').hide(); 
     div.show(); 
    }); 
}); 

http://jsfiddle.net/uwt73sj3/

var selIndex = $("#contact-location").prop('selectedIndex');這裏我們選擇元素索引設置爲變量,我們可以以後工作​​。

$("#contact-location").prop(selIndex).remove();從選擇下拉列表中刪除索引值。

+0

這是完美的,謝謝你瞭解我的壞英語和解決方案:) – Raihan 2014-09-05 20:21:22

0

就可以得到所選擇的選項是這樣的:

$("option:selected", this); 

從那裏,你可以隱藏或刪除它:

$("option:selected", this).hide(); 
$("option:selected", this).remove(); 
1

你可以嘗試這樣的:

$(document).ready(function() { 
     $('#contact-location').change(function(){ 
      $('#contact-location option').show(); //clean alls 
      $('option:selected',this).hide(); // hide selected 
      var location = $(this).val(), 
      div = $('#' + location); 

      $('div').hide(); 
       div.show(); 

     }); 
}) 

LIVE DEMO

+0

我想完全刪除選項列表。就像the_pete給出的例子一樣。對不起,我英語不好。可能是我解釋不好。 – Raihan 2014-09-05 20:23:05

+0

@Raihan別擔心。 :) – 2014-09-05 20:30:07

1

爲什麼不在同一時間使事物更通用?

$(function() { 
    $('#contact-location').change(function() { 
     var $this = $(this); 

     // show only correct location 
     $('div').hide(); // maybe use a class rather than hiding every <div> 
     $('#' + $this.val()).show(); 

     // show only alternate options 
     $this.find('option').show(); 
     $this.find('option:selected').hide(); 
    }); 
}); 
1

一個解決方案是使用點擊選擇(即選項)的孩子,然後隱藏(這是選項)。然後,選擇的值仍然具有所選選項的值,並且您必須手動重置它(我通過css:first-child選擇器使用了第一個孩子的內容,但您也可以使用其他任何內容)。

$(document).ready(function(e) { 
    $('#contact-location').children().click(function(){ 
     var $select = $(this).parent(); 
     var $clicked = $(this); 
     var location = $clicked.val(); //is the same like $select.val() 
     var $div = $('#' + location); 

     $clicked.hide(); 
     $select.val($select.children(":first-child")); 
     $div.show(); 
    }); 
}); 

我在$之前使用了一些變量的名稱來表示這些變量存儲jQuery對象。