0

I've got an ASP.Net TextBox that I want to pass it's text value to a JavaScript function. I've tried several different methods, including the one at this answer, Getting Textbox value in Javascript but my value is always returned as undefined. These textboxes are part of an <asp:UpdatePanel> but I have tried this outside of the panel, and receive the same error.

This is my current code setup:

ASP.Net

<asp:TextBox ID="txtEmail" runat="server" ClientIDMode="Static" 
    CssClass="login-boxes" TextMode="Email" MaxLength="255" ValidationGroup="rPage1" />

<asp:TextBox ID="txtTest" runat="server" ClientIDMode="Static"
    CssClass="login-boxes" ValidationGroup="rPage1" />

<asp:Button ID="btnAdvance" runat="server" CssClass="login-buttons reg-btn-show" 
    OnClientClick="testFunction()" UseSubmitBehavior="false" Text="Advance" 
    OnClick="btnAdvance_Click" ValidationGroup="rPage1" />

JavaScript

var box1 = document.getElementById('<%= txtTest.ClientID %>').value;
var box2 = document.getElementById('<%= txtEmail.ClientID %>');
        
function testFunction() {
    box2.value = box1;
}

What I am trying to achieve, is if I type "Hello" into txtTest and click btnAdvance, it should populate txtEmail with "Hello". How can I achieve this?

Karan
  • 12,059
  • 3
  • 24
  • 40
RazorKillBen
  • 561
  • 2
  • 20
  • `box1` will be set at the beginning and it won't update. So when you click `btnAdvance` it will not have updated value of `txtTest`. Try moving those `box1` & `box2` inside `testFunction`. It should work. – Karan Aug 19 '20 at 10:54
  • Thank you so much, that's exactly what the issue was. That oversight had me going for hours. If you want to submit as an answer, I'll accept, thanks again! – RazorKillBen Aug 19 '20 at 11:34

1 Answers1

1

box1 will be set at the beginning and it won't update. So when you click btnAdvance it will not have updated value of txtTest. Try moving those box1 & box2 inside testFunction. It should work.

function testFunction() {
    var box1 = document.getElementById('<%= txtTest.ClientID %>').value;
    var box2 = document.getElementById('<%= txtEmail.ClientID %>');
    box2.value = box1;
}
Karan
  • 12,059
  • 3
  • 24
  • 40