【问题标题】:Update an asp:TextBox when a asp:ListBox changes selected item当 asp:ListBox 更改所选项目时更新 asp:TextBox
【发布时间】:2015-03-12 22:40:44
【问题描述】:

我是 ASP.Net 新手,我有以下疑问:
当 ListBox 的选定项发生更改时,有没有办法更新 TextBox 的内容? 我有这个:

<asp:ListBox ID="myListBox" runat="server" Width="200px"></asp:ListBox>

&lt;asp:TextBox ID="myTextBox" runat="server" Width="200" /&gt;

ListBox 上的项目是添加到 Page_Load 中的字符串。
基本上,我想将所选项目放在 TextBox 中,而不必进行 PostBack 并在代码隐藏中执行此操作(为了提高效率)。
提前致谢!

【问题讨论】:

    标签: c# asp.net textbox listbox


    【解决方案1】:

    是的,当然。这就是客户端编程的用途(JavaScript)。

    当服务器将ListBox 呈现为 HTML 时,它会转换为 HTML select 元素。所以你可以使用这个代码:

    <asp:ListBox ID="myListBox" runat="server" Width="200px"></asp:ListBox>
    <asp:TextBox ID="myTextBox" runat="server" Width="200" />
    
    <!-- Below we're adding the reference to jQuery, which is publicly hosted on a CDN -->
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    
    <!-- Here's where our JavaScript is -->
    <script type="text/javascript">
    $(function(){
        $('#<%=myListBox.ClientID %>').change(function(){ //when the select value of the list box changes, we're going to call the below code
            $('#<%=myTextBox.ClientID %>').val($('#<%=myListBox.ClientID %>').val()); // Set the value of the text box to the value of the list box.
        });
    });
    </script>
    

    请注意,我使用的是 jQuery 库,这是一个非常流行的 JavaScript 框架,它使客户端编码更容易。

    请注意,我使用特殊语法将 ClientIDListBoxTextBox 嵌入到 JavaScript 中。这是因为 JavaScript 在客户端运行,ListBoxTextBox 的 ID 可以根据 ClientIDMode 从服务器更改为客户端(这让很多 Web 窗体开发人员感到困惑) ) 控制已指定。嵌入 ClientID 确保客户端 JavaScript 中使用的 ID 与客户端上 select 元素的 ID 匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2021-06-08
      相关资源
      最近更新 更多