Validating an input type field against a select

Asked

Viewed 1,108 times

3

I am working with Codeigniter/Bootstrap and need to validate one field of my form according to 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 SIM option is selected in select, the completion of the Datacontract field becomes mandatory.

  • Use javascript for this.

2 answers

1

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

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" 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>

0


P/ validate sending entities, make it mandatory to assign required to the Datacontract field depending on the value of select Contract. I would use Jquery:

´$(function(){
    $('#IdContrato').change(function(){
     if($('#IdContrato').val()==='Sim'){
      $('#IdDataContrato').prop('required', true);
     }
    });
});´

It is also possible to make a conditional validation after sending (See in the manual) if vc is validating in the controller/method. Simply create a value-dependent condition sent within the $this->form_validation->run validation rules().

  • 1

    It worked perfectly. Ball show, thank you !!!!

Browser other questions tagged

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