skip to Main Content

When I update the Input Text field in a web forms application with the javascript method, the change method in the code does not work.
How can I do that?

<asp:TextBox ID="Value1" Columns="2" MaxLength="3" Text="1" runat="server" OnTextChanged="Value1_TextChanged"/>
    
    <button onclick="changeText()">sample</button>
    <script>
    function changeText(){
       $("input[id$='Value1']").val("Change Value!");
    }
    
    </script>
``

And this page’s cs side:

protected void Value1_TextChanged(object sender, EventArgs e)
            {
                string test="this works";
            }

How does the Value1_TextChanged method work in after the changeText method works in javascript?

2

Answers


  1. Well, probably best to just do this:

            Js change text box<br />
            <asp:TextBox ID="TextBox7" runat="server" Width="262px"
                onchange="mytextboxchange(this)"
                ></asp:TextBox>
    
            <asp:Button ID="cmdText7" runat="server" Text="Button" ClientIDMode="Static"
                OnClick="cmdText7_Click" style="display:none"
                />
            <script>
    
                function mytextboxchange(btn) {
    
                    console.log("client side text 7 runs")
                    $('#cmdText7').click()
    
                }
    

    And then you have code behind as

        protected void cmdText7_Click(object sender, EventArgs e)
        {
            Debug.Print("Server side text 7 changed");
        }
    

    you could try a __doPostBack("Mytext7","")

    But, if there are no controls on the page that need/have a post-back, then the _doPostBack() stub is not automatic added, and it gets messay.

    So, just drop in a button. Add the button click event, then hide it with display:none, and you done. You don’t have to do a text changed event that often, so above will should suffice.

    Login or Signup to reply.
  2. Since programmatically changing the value of an input doesn’t fire its change event, so you need to trigger change event manually to make it post back to server side event. You could update your changeText function like this

    function changeText(){
       $("input[id$='Value1']").val("Change Value!");
       // trigger event change manually
       $("input[id$='Value1']").trigger("change");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search