Home > Enterprise >  Disabling button until condition is met (javascript)
Disabling button until condition is met (javascript)

Time:04-09

I'm not sure how to make a button disabled until a variable is equal to a number. In this case, I am trying to make the button disabled unless Cash is equal to 1.

<html>
<body>
    <button>Tester</button>
</body>
<script>
    var Cash = 0;

    if (Cash = 1) {
        btn.disabled = false;
    } else {
        btn.disabled = true;
    }
</script>
</html>

CodePudding user response:

var Cash = 0;
while(true) {
    if (Cash = 1) {
        btn.disabled = false;
    } else {
        btn.disabled = true;
    }
}

This will make it constantly check whether Cash is 1. In your current code, it will only check when the page is first loaded.

CodePudding user response:

Ignoring proxies, no, what you are trying to do here is not really possible with how you are going about it.

What you should do instead is to create a function that changes the value of cash.

var Cash = 0;
function updateCash(newCash){
    Cash = newCash;
    if (Cash===1) {
        btn.disabled = false;
    } else {
        btn.disabled = true;
    }
}
updateCash(10);

You should know that

  • The equals sign = is for assignment. Your if statement actually ends up setting cash to 1. Use the (strict) equality operator instead ===
  • You can shorten enabling btn to btn.disabled = cash!==1
  • Use let instead of var and cash should be lowercase.

Please do not use while(true) under any circumstances. Since javascript is single threaded, this means that anything else that is running, including changing cash will never happen because it is stuck in the loop. You will probably find that the fans on your computer will begin spinning very loudly.

CodePudding user response:

you need to get the button element first by using document.querySelector

let btn = document.querySelector('button') 

You can read about querySelector here.

now when you selected the element you need to make sure that you're using == in your if condition instead of =

== is for comparing value = is for assigning value

Difference between = and ==

now you're code should look like this and it should disabled the button.

let cash = 0;

if (cash == 1) {
  btn.disabled = false;
} else {
  btn.disabled = true;
}

You can check this codepen

  • Related