user1605859 user1605859 - 2 years ago 112 Question

java script code to insert the desired text in a TextBox in

I want to use a java script code to insert a desired word in a

when an
is clicked. The
may have some texts before inserting the desired word. I used the below VB.NET code and it works fine but I want to do it in the client seide. How is it possible? (I am new with java script)

Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim emoticsign As String = TextBox2.Text & ":)"
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.[GetType](), "myScript", "document.getElementById('" + TextBox2.ClientID & "').value = ' " & emoticsign & "';", True)
End Sub

Answer Source

Just target the element by the id and set the value.


 function insertText() {
     document.getElementById("Hello").value = "This is inserted";


<asp:TextBox runat="server" ID="Hello"></asp:TextBox>
<asp:ImageButton runat="server" Text="Insert" OnClientClick="insertText()" />

If you are wanting to handle text already being in this textbox and just append to it then you could add an if/else, so something like:

 function insertText() {
    var textbox = document.getElementById("Hello")
    if(textbox.value != "") {
        textbox.value = textbox.value + " text appended";
    else {
            textbox.value = "This is inserted";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download