简体   繁体   中英

How to call javascript function from asp:textbox?

I am using textbox for searching items from data base and loading them in gridview and

i used custom paging on gridview to show only 25 records per page

and i found java script for searching records on client side as

script>
        function filter2(phrase, _id) {
            var words = phrase.value.toLowerCase().split(" ");
            var table = document.getElementById(_id);
            var ele;
            for (var r = 1; r < table.rows.length; r++) {
                ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
                var displayStyle = 'none';
                for (var i = 0; i < words.length; i++) {
                    if (ele.toLowerCase().indexOf(words[i]) >= 0)
                        displayStyle = '';
                    else {
                        displayStyle = 'none';
                        break;
                    }
                }
                table.rows[r].style.display = displayStyle;
            }
        }

    </script>

and calling this as:

<input name="txtTerm" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" type="text"/>

this function search record from activated page and obviously searching from whole database will be done on server side and i used asp textbox

but i need onkeyup="filter2(this, '<%=GridView1.ClientID %>')" event in my asp textbox eg

 <asp:TextBox ID="txtSearch" onkeyup="filter2(this, '<%=GridView1.ClientID %>')"  placeholder="Search" runat="server"  AutoPostBack="True" OnTextChanged="txtSearch_TextChanged" />

but asp didn't allow me to do that..

i need your help to achieve this.

thanks in advance.

EDIT:

I need both searching (client side, server side) in single textbox because

client side allow searching from loaded page of gridview and

server side allow searching from database on clicking

You could add the client attribute of rendered input control via code behind:

protected void Page_Load(object sender, EventArgs e)
{

    txtSearch.Attributes.Add("onkeyup", string.Format("filter2(this,'{0}')",GridView1.ClientID)");
}

EDIT:

After the right comment of @Lukas, we should say that the main problem was the use of <%=GridView1.ClientID %> inline expression inside the textbox webcontrol:

<%= %> will write the string directly to the response-stream, which happens after the server control is constructed, so will be rendered as string and not resolved.

For example:

<asp:Label runat="server" ID="label">test</asp:Label>
    <asp:TextBox runat="server" ID="txt" Text="<%# label.ID %>" onkeyup="alert('<%: label.ID %>')"></asp:TextBox>

This is what we have in output:

在此处输入图片说明

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