2015-12-08 88 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. 
} 

} 
相关问题