简体   繁体   中英

Testing if a button has been clicked or not

I have an asp.net page which loads and writes values from a record to the controls on the page.

There is a link to another page and a save button.

If the user clicks save, fine, the changes are saved and they can navigate to wherever.

If they dont click save and click the link, any changes are lost.

Is there a way to check if the save has been clicked while the user has that page loaded?

I'm thinking along the lines of an OnClick Javascript function for the link such as -below, I'm not sure though how to test for the save button being clicked - can anyone point me in the right direction?

function handleHyperLinkClick(hyperlink) 
{ 
    confirm("You have not clicked save, any changes will be lost - click cancel then save  your changes or ok to continue");
 } 

Add a bool variable, that is default false, set to true if the button has been clicked. Then check the value if user leaves the page.

You can do using hidden field . when user click on save button then set hidden field value.

You have to keep a temporary variable in javascript like state;

`

var state = 0;

 //your function calls here
function yourFunction()
{
//// your coding
 state =1;
//// your coding
}

` In this case, you have to submit the value or navigate to other page when state=1, otherwise you shouldnt. This flag to be checked whilst clicking link (if its navigating via function) or onBeforeUnload event for page.

Please correct me know if you are looking for something other.

You can attach some value to a variable when the button is clicked. Then when the user tries to navigate, check whether that variable has that value. If so, it has been clicked, else not:

button = document.getElementById("button");
button.onclick = function() { clicked = true; }
document.getElementById("link").onclick = function() { if (!clicked) { alert("Sure?"); }

Assuming you are using ASP.NET server buttons like this:

<asp:Button runat="server" id="someButtonId" Click="someClickHandler" Text="Continue" />

If I were you, I would use jQuery to dynamically bind the click event of the button like this:

$(document).ready(function() {
   $("input[type=button][id$=someButtonId]").on("click", function(e) {
      if(!confirm("You have not clicked save, any changes will be lost - click cancel then save  your changes or ok to continue"))
      {
          e.preventDefault()
      }
   });
});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM