How to enable or disable an input according to a select html javascript option?

Asked

Viewed 6,698 times

0

I want an input to start disabled and when the person select for example a certain option of select the input is enabled.

  • Can you describe what you’ve tried?

  • I’m looking for help. I don’t know much javascript

  • Then start reading about the method addEventListener and the event change of your field select.

  • Put what you already have of html/css/js code that already helps you answer.

2 answers

3


Well you can take as a basis this example:

function verifica(value){
	var input = document.getElementById("input");

  if(value == 2){
    input.disabled = false;
  }else if(value == 3){
    input.disabled = true;
  }
};
<!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    <input type="text" name="input" id="input" disabled>
    <br><br>
    <select id="options" onchange="verifica(this.value)">
    <option value="1" selected>1 - Não interfere</option>
    <option value="2">2 - Habilita</option>
    <option value="3">3 - Desabilita</option>
    </select>
    </body>
    </html>

1

Selecting option = Voley the input shall be enabled.

Utilize getElementById to identify each element within the form.

To recover the value of the selected option

document.getElementById("jogos").value; 

If you have this value, enable or disable the input.

 function validarForm() { 
       var optionSelect = document.getElementById("jogos").value;

       if(optionSelect =="3" ){ 
           document.getElementById("btn").disabled = false;
       }else{
           document.getElementById("btn").disabled = true;
       }
}
    <form method="post" action="/"> 
    <select name="jogos" id="jogos" onchange="validarForm()">
    <option value=''>Selecione o esporte</option>
    <option value='1'>Futebol</option>
    <option value='2'>Tenis</option>
    <option value='3'>Voley</option>
    </select>
    <input type="text" id="btn" disabled>
    </form> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.