Assign a value to an ASP Text Box using JavaScript

0

This is my function JavaScript :

function prueba() {
    var a = 1;
    var b = 2;
    var total = a + b;
    ('#TextBox1').val(total);
}

This is the .aspx :

    <div>
       <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
    </div>

And this aspx.cs :

namespace widget
{
    public partial class _Default : Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, GetType(), "mifuncion", "prueba()", true);

        }


    }
}

And I want to assign the value of "total" in the Textbox .

    
asked by Ernesto Emmanuel Yah Lopez 13.06.2017 в 19:58
source

3 answers

1

If you are using JQuery you are missing the $

function prueba() {
    var a = 1;
    var b = 2;
    var total = a + b;
    $('#TextBox1').val(total);
}
    
answered by 13.06.2017 в 20:52
1

You can do the following:

JavaScript function to assign the value to the TextBox:

   function TuFuncionJS() {
        var a = 1;
        var b = 2;
        var total = a + b;
        var valorTxt = document.getElementById("<%=Txt1.ClientID%>").value = total;
    }

In the CodeBehind if you want the text to be assigned to the TextBox in the Load event, add the following:

    protected void Page_Load(object sender, EventArgs e)
    {     
        ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "TuFuncionJS();", true);
    }

In the aspx.cs:

<asp:TextBox ID="Txt1" runat="server"></asp:TextBox>

I hope you serve, any questions do not hesitate to ask me.

    
answered by 14.06.2017 в 22:51
0

What happens is that you are using Master Page; this implies that every ID that you put on the server side, when you paint in HTML, you add a "" MainContent_ "to the beginning of the id because it is a segment of html that you are embedding in the master page.

One option is to leave the complete id like when you paint "MainContent_Texbox1".

The second one is something like this:

$("#" + "<%= TextBox1.ClientID %>").val(total);

ClientID property information

    
answered by 13.06.2017 в 23:46