php – Validating an input field as a function of a select

Question:

I'm working with Codeigniter/Bootstrap and I need to validate a field on my form against another. I have a select field called Contract, with two possible options (Yes or No) and another input field called DataContract. I need that when the option YES is selected in the select, filling out the DataContract field becomes mandatory.

Answer:

I made a basic example, I don't know if it's the best way, but it works.

<!DOCTYPE html>
<html>

  <head>
    <link href="style.css">
    <script>
    
      function ativarInputDataContrato(){
        var lista = document.getElementById("lista-boolean-contrato");
        var input = document.getElementById("data-contrato");
        if(lista.value == "Sim"){
          input.disabled = false;
          input.required = true;
        }else{
          input.disabled = true;
          input.required = false;
        }
      }
      
      
    </script>
  </head>

  <body>
    <form id="formulario">
      Contrato:
       <select id="lista-boolean-contrato" onchange="ativarInputDataContrato()">
         <option value="Nao">Não</option>
         <option value="Sim">Sim</option>
         
       </select>
       <input id = "data-contrato" type = "date" disabled required="true" />
       <input type = "submit" value = "Enviar"/>
     </form>
  </body>

</html>
Scroll to Top
AllEscort