简体   繁体   中英

Updating Global Counter Variable on Submit Button Click in jQuery

I'm trying to update a global counter variable in JavaScript when a button of type="submit" is clicked.

My submit button is defined like below:

<button
  id="submitClicked"
  type="submit"
  value="Add &amp View Next"
> 

I am using the following code in JavaScript to update a global variable I've called orderCounter that increments each time the "Add & View Next" button is clicked:

var orderCounter;

window.onload = function () {
  document
    .getElementById("submitClicked")
    .onclick=incrementCounter;
};

function incrementCounter() {
  if (orderCounter == null) {
    orderCounter = 0;
  } else {
    orderCounter = orderCounter + 1;
  }

  alert(orderCounter);
  return orderCounter;
}

The alert with this code always displays 0. Can anyone see where I'm going wrong?

Note: I've also tried using jquery .click on the submitClicked id in addition to using onClick within the HTML form.

I realize this should be simple; not sure where I'm going wrong.

Thank you!

the problem is that every time you click on the submit button your page refreshes, so the orderCounter varriable resets itself. one solution is to persistently wait so that its value is not reinitialized each time the page is loaded. One solution is to use kookies: https://www.w3schools.com/js/js_cookies.asp . i hope this will welp you

The fix was to run function postValues() "onClick" of button type=submit and use session variables, following the same logic as in this post: Auto Increment in Session using Javascript is not working

I clear the sessionStorage variables in another file.

Working code:

function postValues() {

if(sessionStorage.getItem("count") == null){

  counter=sessionStorage.setItem("count", 1);
  counters = 1;

} else {

  counters= parseInt(sessionStorage.getItem("count")); 
  counters++;
  counter=sessionStorage.setItem("count", counters);

}

alert(counters);

document.getElementById("counter").value = counter; 

}

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