0

I have a variable I'm setting to true, then later checking things in a couple different functions and re-setting it to false if a check fails.

Setting it here...

$(document).ready(function() {
    //Set enable_submit to true, then run checks to see if it should be reset to false
    var enable_submit = true;
}

Doing other checks. Then, seeing if it's still true or not here...

function change_submit_button_state() {
    if (enable_submit == true) {
        $("button[type=submit]").prop("disabled", false);
    } else {
        $("button[type=submit]").prop("disabled", true);
    }
}

The problem is I'm getting a "ReferenceError: enable_submit is not defined" and the line referenced in the error is the if (enable_submit == true) { line from above.

Is there a way around this?

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
gtilflm
  • 1,389
  • 1
  • 21
  • 51
  • This was closed, but in my opinion the best answer to this would be to store the state with `data` on the button, and then just access that. It's availble everywhere, and avoids globals – adeneo Sep 16 '17 at 18:11
  • @adeneo: Do you have a reference for your idea? Not sure what "store the state with `data` on the button" means. – gtilflm Sep 16 '17 at 18:12
  • https://jsfiddle.net/adeneo/5gg33hvw/ – adeneo Sep 16 '17 at 18:28

1 Answers1

2

You should just wrap the function within document.ready method.

$(document).ready(function() {
   //Set enable_submit to true, then run checks to see if it should be reset to false
   var enable_submit = true;
   function change_submit_button_state() {
     if (enable_submit == true) {
        $("button[type=submit]").prop("disabled", false);
     } else {
        $("button[type=submit]").prop("disabled", true);
     }
   }
}

In your code enable_submit variable has a local scope .

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128