0

I want to disable button if user didnt add anything into global variable "code". I tryied indexOf() however it is reactive only once. Lets say if i have button that adds "z" into "code" global variable, it does not execute function inside indexOf("z"); Can anybody help?

let code = "";

$(document).ready(() => {
      function codeCheck() {
        if (code = "") {
          console.log("nothing")
        } else if (code.indexOf("z")) {
          console.log("do semething")
        }
      }

      code = "z";
      codecheck();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Chris G
  • 7,957
  • 4
  • 17
  • 29
Zyonix
  • 107
  • 10

3 Answers3

1

You should rather use the includes function to check if your string contains a substring

let code = "";

$(document).ready(() => {
  function codeCheck() {
    if (code == "") {
      console.log("nothing")
    } else if (code.includes("z")) {
      console.log("do something")
    }
  }

  code = "z";
  codeCheck();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Islam Elshobokshy
  • 8,788
  • 6
  • 20
  • 45
0

To compare the value of your var in the if condition you have to use == or === operator. Your are using the assigment operator.

let code = "";

$(document).ready(() => {
    function codeCheck() {
        if (code === "") { // <--
            console.log("nothing")
        } else if (code.indexOf("z") > -1) {
            console.log("do semething")
        }
    }

    code = "z"; 
    codecheck();
});
hawks
  • 461
  • 4
  • 12
-1

You need to figure out how the value "code" is being updated. If it's via a button, add an EventListener that calls the codeCheck method. In the following snippet I used a jQuery change function.

let code = "";

$(document).ready(() => {
  $("#myCode").change( function(ev) {
     let newVal = ev.target.value; // this will contain the value in the textbox
     code = newVal;
     codeCheck();
  });
  function codeCheck() {
    if (code == "") {
      console.log("nothing")
    } else if (code.includes("z")) {
      console.log("do something")
    }
  }
});
<input type="text" id="myCode" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can then iterate over the above approach and add a button.

<button onClick="addZToMyCode()">Add Z</button>
//JS
function addZToMyCode() {
  code += "z";
  codeCheck();
}

AFAIK I don't think we can put an event listener to a variable in JS. Edit: found this answer on Stackoverflow that you might be interested in.

Tenzin Kunkyab
  • 137
  • 2
  • 8