简体   繁体   中英

Accessing asp:Textbox value inside an asp:Datalist control using Javascript

I am having major difficulty in accessing the text value of an asp:textbox control that is inside an asp:Datalist control. Here is the code:

<asp:DataList id="UserIP" DataSourceID="dsGetData" runat="server" CssClass="lblText">
 <ItemTemplate>                 
<span class="lblText">IP Address:</span><br />
     <asp:TextBox ID="tbUserIP" class="textbox_medium" runat="server" AutoPostBack="false" Text='<%# Eval("[IPAddress]") %>' /></asp:TextBox>
 </ItemTemplate></asp:DataList>

I am assigning the Textbox a value from the results of a SQL query. Then I need to get that value of that Texbox using Javascript. My JavaScript code is below:

var temp =  document.getElementById("<%= UserIP.FindControl("tbUserIP").ClientID %>");

I keep getting compilation error: The name 'tbUserIP' does not exist in the current context

Any help would be appreciated tremendously.

The problem with your code is that, when you call UserIP.FindControl("tbUserIP").ClientID the tbUserIP is not available.

Notice that, to have access to such control, you will have to invoke DataBind over UserIP DataList first and only after that, maybe you will have some results that will result in rows with text boxes called tbUserIP .

To solve that, and because there are so many ways to solve it, I suggest you give a look to this: ASP.NET Page Event Life Cycle , so you can get a clear notion of what step are you probably missing in your way to accomplish what you want.

Alternatively, and not relying so much on the ASP.NET page processing, you can work your javascript to deal with what you know that will be the end result.

Which is:

  • If your DataList has results, you will have something like this <input type="text" id="$somecontainerid$1$tpUserIP" value="192.168.0.1"/> in your resulting HTML right?!

  • So, to grab that on your javascript, assuming you can use jQuery, you can do something like this:

// grabs all the input fields with id tpUserIP (of the multiple rows).

$ipaddressFields = $("input[id*=tpUserIP]");

// alerts each one of them, if any, to show that it works.

if($ipaddressFields.length > 0){

 $ipaddressFields.each(function(){ alert($(this).val()); }); 

}

Here's how you'd do it in JavaScript without using JQuery. I'm not sure from where you'd call the JavaScript function. So, I'm giving you two examples. Ie one is onclick of a TextBox and the other is onclick of a button.

Here's the HTML markup

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
    function Test(obj) {
        alert(obj.id); // This is the ID of the textbox clicked on
        alert(obj.value); // This is the value of the textbox clicked on
    }

    function Test2() {
        var dataListid = '<%= UserIP.ClientID %>';
        var obj = document.getElementById(dataListid);
        if (obj != 'undefined' || obj != null) {
            for (var i = 0; i < obj.getElementsByTagName('input').length; i++) { // Loop through all TextBoxes (input elements if we talk in markup language)
                alert(obj.getElementsByTagName('input')[i].value); // Here are the values of each textbox
            }
        }
    }

</script>
    <form id="form1" runat="server">
    <div>
        <asp:DataList id="UserIP"  runat="server" CssClass="lblText" >
            <ItemTemplate>                 
            <span class="lblText">IP Address:</span><br />
                <asp:TextBox ID="tbUserIP" class="textbox_medium" runat="server" AutoPostBack="false" Text='<%# String.Concat("Test", (Convert.ToInt32(Container.ItemIndex)+1))%>' onclick="Test(this);" /></asp:TextBox>
            </ItemTemplate>
        </asp:DataList>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Test2();" />
    </div>
    </form>
</body>
</html>

And here's the code behind I used. You may use your own code to bind the DataList.

using System;
using System.Collections.Generic;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<string> ips = new List<string>() {"1", "2", "3"};
        UserIP.DataSource = ips;
        UserIP.DataBind();

    }
}

Hope this helped.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM