1

I want to call a method hello() in javascript from aspx.cs ( c# ) when a listbox1 item is selected.Using this code to do it but not working

protected void ListBox1_TextChanged(object sender, EventArgs e)
    {
        ClientManager.RegisterStartupScript(this, GetType(), "whatiskey","hello();", true); 
    }

    function hello() {
alert("hiiiii");
 var arr = ["<%=myvalue %>"];


            }
6
  • Not working means? are you getting any error message Commented Jan 20, 2016 at 9:41
  • No error , just the method not executed Commented Jan 20, 2016 at 9:42
  • try : Page.ClientScript.RegisterStartupScript( GetType(), "whatiskey", "hello();", true); Commented Jan 20, 2016 at 9:44
  • @Zaki not working , does the key parameter has to do something with it as I have no key defined at javascript its just a method Commented Jan 20, 2016 at 9:49
  • try ClientManager.RegisterStartupScript(this, GetType(), "whatiskey","javascript:hello();", true); and also put an alert on the first line of the method. And also check console for any error Commented Jan 20, 2016 at 9:53

2 Answers 2

2

Setting "AutoPostBack" property of ListBox to "true" and using Page.ClientScript.RegisterStartupScript(GetType(), "whatiskey", "hello();", true); worked for me

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry for marking it unanswered , the page is being refreshed but the method is not being called
@phpnet Can you provide "hello" method declaration, please? Where is it declared?
@phpnet Javascript is enabled in browser? That still works fine for me
Yes it is , thank you for your reply I think there is some other problem at my side
1

use

Response.Write("<script>hello();</script>");

EDIT

if all you wanna do is call a javascript on selection of an item, you can use onchange attribute as follows -

<asp:ListBox onchange="hello();" ID="ListBox1" runat="server">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>

    </asp:ListBox>
    <script>
        function hello() {
            alert("hello");
        }
    </script>

1 Comment

have you set EnableAutoPostBack property of ListBox to true ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.