Home > Mobile >  Disable and enable button by over or under age 18 Javascript
Disable and enable button by over or under age 18 Javascript

Time:11-14

Im new to JavaScript.

I struggled to find solution of enable and disable button using by if statement of under and over age 18, first click vote button was enable when I insert number 10 on textbox then disable button is stuck and cant change to enable after change the number of over age 18.

        //age verification

            if(Age < 18)
            {
            document.getElementById('age').style.borderColor='#e52213';
            document.getElementById("Btn").disabled = true;
            }
            if(Age > 18)
            {
                document.getElementById("Btn").disabled = disabled;
            }

Check image of vote button stuck on webpage at below:

enter image description here

CodePudding user response:

You can assign false to the disabled attribute. Also, you should enable the button when the value is >=.

Demo:

var ageEl = document.getElementById('age');
ageEl.addEventListener('input', function(el){
  var age = ageEl.value;
  console.log(age)
  if(age < 18){
    document.getElementById('age').style.borderColor='#e52213';
    document.getElementById("Btn").disabled = true;
  }
  else if(age >= 18){
    document.getElementById('age').style.borderColor='';
    document.getElementById("Btn").disabled = false;
  }
});
<input type="number" id="age">
<button id ="Btn">My Button</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The disabled property is a Boolean so something like

btn = document.getElementById("Btn")

if(Age <= 18)
{
    document.getElementById('age').style.borderColor='#e52213';
    btn.disabled = true;
}
else if(Age > 18)
{
    btn.disabled = false;
}

also a couple of other things, you should use else if instead of another if so you don't check for something you already know is false,

use <= for the case where the age is 18

and also probably better imo to save the btn to a variable so you dont fetch the element twice.

  • Related