Douglas Moura
Douglas Moura

Reputation: 43

Call javascript after a code behind function has just populated a text box

I have an aspx page with an asp button that calls a function from code behind in order to do some some stuff involving DLL files. The output of the function is stored in a textbox. I'd like to call a javascript function just after this textbox is filled up. None of the below attempts worked. Any tips?

<asp:TextBox ID="TextBox2" runat="server" Width="300px" onchange="javascript:Draw();"></asp:TextBox>

<input type="text" size="20" id="TextBoxHtml" runat="server" onchange="Draw()" /></td>

<input type="text" size="20" id="TextBoxHtml" runat="server" onblur="Draw()" /></td>

Summary of the code:

//File chart.aspx
<!DOCTYPE html>
<html>
<head runat="server">

</head>
<body>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Process" Width="100px" />
<asp:TextBox ID="TextBox2" runat="server" Width="300px" ></asp:TextBox>

<script src="JavaScript.js"></script>
</body>
</html>

//File chart.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
    //Do some stuff ...
    TextBox2.Text = "200"; 
}

//File: JavaScript.js
function Draw() {
    //Do some stuff ...
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById("MainTool_TextBox2").addEventListener('change', function () {
        Draw();
    });
});

Upvotes: 3

Views: 1293

Answers (2)

VDWWD
VDWWD

Reputation: 35544

The TextBox is already filled with content after PostBack, so onchange or onblur are never triggered client side.

You can call it from code

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "callDraw", "Draw()", true);

Or check if the value is not empty and call Draw like this.

<script>
    $(document).ready(function () {
        if ($('#<%= TextBox2.ClientID %>').val() !== '') {
            Draw();
        }
    });
</script>

Upvotes: 0

MPawlak
MPawlak

Reputation: 715

Try waiting until the DOM is loaded, then attach the event listener to the element.

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("TextBox2").addEventListener('change', function() {
        draw();
    });
});

Upvotes: 0

Related Questions