2015-12-08 91 views
0

我想從現有下拉列表中填充dropdown2。我正在使用它的類來定位這個下拉菜單。添加選項以使用現有下拉列表選擇

此外,要將選定的選項從下拉列表中添加到dropdown2。

<asp:DropDownList ID="DropDownList1" runat="server" class="dropdown" EnableViewState="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList> 

       <select class="dropdown2"></select> 

然後,在變化,我有這樣的:

$(".dropdown").change(function() { 
    var selectedText = $(".dropdown option:selected").text(); 
    var selectedValue = $(".dropdown option:selected").attr('value') 

    $('.dropdown option').each(function() { 

     $(".dropdown2").append(new Option($(this).text(), $(this).attr('value'))); 
    }); 

    $(".dropdown2 option:contains(" + selectedText + ")").attr('selected', 'selected'); 
}); 

如何填充選擇並添加使用現有的下拉列表選項?

+0

它行不通的,因爲你有回發一個asp.net下拉列表。你的js邏輯永遠不會執行。 – DinoMyte

+0

我需要下拉後發回,因爲我有轉發器綁定更改選擇... – n00bie

回答

0

由於你正在使用asp.net下拉列表,你需要做一些破解工作。 Asp.net事件將取代任何js事件並自動觸發回發。

ASPX:

<asp:DropDownList ID="DropDownList1" runat="server" class="dropdown" EnableViewState="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList> 
<select class="dropdown2"></select> 
<script> 
var valueChanged = '<%=ValueChanged%>'; // get the server side variable and assign its value to a js variable 
$(document).ready(function() { 
    if(valueChanged.toLowerCase() == 'true') 
    { 
    var selectedText = $(".dropdown option:selected").text(); 
    var selectedValue = $(".dropdown option:selected").attr('value') 

    $('.dropdown option').each(function() { 
    $(".dropdown2").append("<option id="$(this).attr('value')">$(this).text()</option"); 
    }); 

    $(".dropdown2 option:contains(" + selectedText + ")").attr('selected', 'selected'); 
    } 
}); 

</script> 

ASPX.CS:

public class Test 
{ 

    public bool ValueChanged = false; // declare a public variable 
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    ValueChanged = true; // set the value to true on index change. 
} 

} 
相關問題