Search code examples
c#javascriptjqueryonbeforeunloadhiddenfield

window.onbeforeunload losing values in text box


I have the following code to check for changes on a form when the user is navigating away

window.onbeforeunload = confirmExit;

confirmExit is a function which handles the check for changes and whether to display a message to the user. However inside the function the textboxes I need to check are losing their values but any hidden fields are not.

Both controls are being set on Page_Load as below in c#:

txtForeName.Text = personDetails.Forename;
ClientScript.RegisterHiddenField("hdnForename", personDetails.Forename);

In the markup within the confirmExit function I'm retrieving the values as below:

if ($("[id$='_txtForename']").val() != $('#hdnForename').val()) {
    return true; }

But as I said the value for the textbox is an empty string while the hidden field has retained its value.

Does anyone know why this might be happening and how to fix it?


Solution

  • Are you sure your selector for the textbox works?

    Try:

    console.log('#<%=txtForeName.ClientID%>').val());
    

    within onbeforeunload and see whether you get the value displayed in the console.