Span tag added with class while retrieving value using jQuery in ASP.Net

Last Reply on Jan 17, 2017 03:34 AM By AnandM

Posted on Jan 12, 2017 01:43 AM

Hi,

I have assigned values to the label using javascript when i click on button all lable values clears.

But i want to fetch all label values on button click.

so please suggest me proper solution.

 

$(function () {
GetCustomers(1);
$("[id*=gvCustomers] tr").click(function () {
//Selected Row.
var selectedRow = $(this).closest('tr');
//In eq(0) portion you need to mention the cell number.
var plid = $(selectedRow).find('td').eq(0).html();
var plsource = $(selectedRow).find('td').eq(1).html();
var pldest = $(selectedRow).find('td').eq(2).html();
var plttype = $(selectedRow).find('td').eq(3).html();
var plsdate = $(selectedRow).find('td').eq(6).html();
var plcontact = $(selectedRow).find('td').eq(8).html();
$('[id*=txtsmsid]').html(plid);
$('[id*=lblsource]').html(plsource);
$('[id*=lbldest]').html(pldest);
$('[id*=lbltrucktype]').html(plttype);
$('[id*=lbldate]').html(plsdate);
$('[id*=lblcontact]').html(plcontact);
$('[id*=btnsendMsg]').show();
});
});

 

<div class="PageDesc">
<div class="form-group">
<div class="col-md-1">
<asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true" Text="Message : "></asp:Label>
</div>
<div class="col-md-10">
<p>
<asp:Label ID="lblsource" runat="server"></asp:Label>
To
<asp:Label ID="lbldest" runat="server"></asp:Label>
<asp:Label ID="lblttype" runat="server"></asp:Label>
Date:<asp:Label ID="lbldate" runat="server"></asp:Label>
Contact:<asp:Label ID="lblcontact" runat="server"></asp:Label>
</p>
</div>

<asp:Label ID="lblsuccess" runat="server" ForeColor="Green" Font-Bold="true" Text="SMS SENT SUCCESSFULLY !" Visible="false"></asp:Label>
</div>
</div>

I am assigning gridview selected row cells values to the label, then i want to send label values to mobile through SMS on button click.

Posted on Jan 13, 2017 02:21 AM

Hi Logic24,

I have created a sample which full fill your requirement

HTML

<div>
    <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID" />
            <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
            <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
        </Columns>
    </asp:GridView>
    <br />
    <div class="Pager">
    </div>
    <br />
    <br />
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                CustomerId:-
            </td>
            <td>
                <asp:Label ID="lblCustomerId" runat="server" />
                <asp:HiddenField ID="hfCustomerId" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                ContactName:-
            </td>
            <td>
                <asp:Label ID="lblContactName" runat="server" />
                <asp:HiddenField ID="hfContactName" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                City:-
            </td>
            <td>
                <asp:Label ID="lblCity" runat="server" />
                <asp:HiddenField ID="hfCity" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
            </td>
        </tr>
    </table>
</div>
<div>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="ASPSnippets_Pager.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            GetCustomers(1);
            $("[id*=gvCustomers] tr").click(function () {
                //Selected Row.
                var selectedRow = $(this).closest('tr');
                //In eq(0) portion you need to mention the cell number.
                var customerId = $(selectedRow).find('td').eq(0).html();
                var contactName = $(selectedRow).find('td').eq(1).html();
                var city = $(selectedRow).find('td').eq(2).html();
                $('[id*=lblCustomerId]').html(customerId);
                $('[id*=lblContactName]').html(contactName);
                $('[id*=lblCity]').html(city);
                $('[id*=hfCustomerId]').val(customerId);
                $('[id*=hfContactName]').val(contactName);
                $('[id*=hfCity]').val(city);
            });
        });
        $(".Pager .page").live("click", function () {
            GetCustomers(parseInt($(this).attr('page')));
        });
        function GetCustomers(pageIndex) {
            $.ajax({
                type: "POST",
                url: "CS.aspx/GetCustomers",
                data: '{pageIndex: ' + pageIndex + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        }

        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var customers = xml.find("Customers");
            var row = $("[id*=gvCustomers] tr:last-child").clone(true);
            $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
            $.each(customers, function () {
                var customer = $(this);
                $("td", row).eq(0).html($(this).find("CustomerID").text());
                $("td", row).eq(1).html($(this).find("ContactName").text());
                $("td", row).eq(2).html($(this).find("City").text());
                $("[id*=gvCustomers]").append(row);
                row = $("[id*=gvCustomers] tr:last-child").clone(true);
            });
            var pager = xml.find("Pager");
            $(".Pager").ASPSnippets_Pager({
                ActiveCssClass: "current",
                PagerCssClass: "pager",
                PageIndex: parseInt(pager.find("PageIndex").text()),
                PageSize: parseInt(pager.find("PageSize").text()),
                RecordCount: parseInt(pager.find("RecordCount").text())
            });
        };
    </script>
</div>

C#

private static int PageSize = 10;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDummyRow();
    }
}

private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("CustomerID");
    dummy.Columns.Add("ContactName");
    dummy.Columns.Add("City");
    dummy.Rows.Add();
    gvCustomers.DataSource = dummy;
    gvCustomers.DataBind();
}

[WebMethod]
public static string GetCustomers(int pageIndex)
{
    string query = "[GetCustomers_Pager]";
    SqlCommand cmd = new SqlCommand(query);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
    cmd.Parameters.AddWithValue("@PageSize", PageSize);
    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
    return GetData(cmd, pageIndex).GetXml();
}

private static DataSet GetData(SqlCommand cmd, int pageIndex)
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds, "Customers");
                DataTable dt = new DataTable("Pager");
                dt.Columns.Add("PageIndex");
                dt.Columns.Add("PageSize");
                dt.Columns.Add("RecordCount");
                dt.Rows.Add();
                dt.Rows[0]["PageIndex"] = pageIndex;
                dt.Rows[0]["PageSize"] = PageSize;
                dt.Rows[0]["RecordCount"] = cmd.Parameters["@RecordCount"].Value;
                ds.Tables.Add(dt);
                return ds;
            }
        }
    }
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblCustomerId.Text = hfCustomerId.Value;
    lblContactName.Text = hfContactName.Value;
    lblCity.Text = hfCity.Value;
    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Alert", "alert('Values Maintained After Page PostBack!!')", true);
}

VB.Net

Private Shared PageSize As Integer = 10
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindDummyRow()
    End If
End Sub

Private Sub BindDummyRow()
    Dim dummy As New DataTable()
    dummy.Columns.Add("CustomerID")
    dummy.Columns.Add("ContactName")
    dummy.Columns.Add("City")
    dummy.Rows.Add()
    gvCustomers.DataSource = dummy
    gvCustomers.DataBind()
End Sub

<WebMethod()> _
Public Shared Function GetCustomers(pageIndex As Integer) As String
    Dim query As String = "[GetCustomers_Pager]"
    Dim cmd As New SqlCommand(query)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.AddWithValue("@PageIndex", pageIndex)
    cmd.Parameters.AddWithValue("@PageSize", PageSize)
    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output
    Return GetData(cmd, pageIndex).GetXml()
End Function

Private Shared Function GetData(cmd As SqlCommand, pageIndex As Integer) As DataSet
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
    Using con As New SqlConnection(strConnString)
        Using sda As New SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand = cmd
            Using ds As New DataSet()
                sda.Fill(ds, "Customers")
                Dim dt As New DataTable("Pager")
                dt.Columns.Add("PageIndex")
                dt.Columns.Add("PageSize")
                dt.Columns.Add("RecordCount")
                dt.Rows.Add()
                dt.Rows(0)("PageIndex") = pageIndex
                dt.Rows(0)("PageSize") = PageSize
                dt.Rows(0)("RecordCount") = cmd.Parameters("@RecordCount").Value
                ds.Tables.Add(dt)
                Return ds
            End Using
        End Using
    End Using
End Function

Protected Sub btnSubmit_Click(sender As Object, e As EventArgs)
    lblCustomerId.Text = hfCustomerId.Value
    lblContactName.Text = hfContactName.Value
    lblCity.Text = hfCity.Value
    ScriptManager.RegisterClientScriptBlock(Page, Me.[GetType](), "Alert", "alert('Values Maintained After Page PostBack!!')", True)
End Sub

Screenshot


Posted on Jan 17, 2017 03:34 AM
Logic24 says:
 var plid = $(selectedRow).find('td').eq(0).html();

while retrieving above id the span tag with class name "highlight" is getting applied so you need to cross check your code from where it is getting applied and remove it as i have cross checked the code and it is working fine.