How to send bound data to js function through onClientClick() Event?

I would like to pass data to js function from onClientClick(). Data I would like to send is

<%# Eval("index") %>

which is bound to addressID.

<asp:Button ID="btnAddress" addressID='<%# Eval("index") %>' runat="server"  OnClick="btnAddress_Click" OnClientClick="clientSide(<%# Eval("index") %>)" Text="Update"/>

js function to be invoked by OnClientClick() is below:

function clientSide(addressid) {
        if (addressid) {
            alert('In');
        }

I have already tried OnClientClick="clientSide(<%# Eval("index") %>)"/> and OnClientClick="clientSide(addressID)"/> None worked.

Answers


Your javascript "if" clause does not match the passed parameter so it will always be false and never alert('In');

change

if (adresed) => to if (addressid)

Or simple change it to

alert(addressid)

With the browser "Developer Tools" you can also place a break point in your javascript function to review the arguments and why the if clause would fail.

You may also want to "return false" to stop the button from doing a postback.

OnClientClick="clientSide(<%# Eval("index") %>); return false;" 

The expression be used for OnClientClick can be change like that,

<asp:Button ID="btnAddress" addressID='<%# Eval("Value") %>' runat="server" 
     OnClientClick='<%#string.Format("return clientSide(\"{0}\");",Eval("Value"))%>'
     Text="Update" 
     />

note that javasctipt function method should return false.


Try it in

<asp:Button ID="btnAddress" addressID='<%# Eval("index") %>' runat="server"  OnClick="btnAddress_Click" OnClientClick='<%# "clientSide(" + Eval("index") + ");return false;"%>' Text="Update"/>

Try it in GridView RowDataBound event

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Label lblIndex = (Label)e.Row.FindControl("index");

                    ((Button)e.Row.FindControl("btnAddress")).Attributes.Add("onclick", "return clientSide('" + lblIndex.Text + "');");
                }

            }

Need Your Help

Deleting all child nodes and text of an element

xml ruby rexml

With reXml using Ruby, I have a particular element and I want to completely clear out all its child nodes and text.