Add "required" attribute after change in "select"

Asked

Viewed 110 times

0

In my system, there are three types of users:

  • General Manager;
  • administrator; and
  • Client.

The Client does not have access to the system, therefore, it does not need password and would not be required your email (since it would not login).

I wish that when the General Manager would choose between Client or Administrator, when selecting Administrator, a input to enter your password, and add the required to the input email; and when selecting Customer, was undone.

I was able to do the show and hide part input, but would like to know how to add the required to e-mail.

$("#tipo").change(function() {
  $('#senha').hide();
  if (this.value == "Administrador")
    $('#senha').show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="tipo" id="tipo">
  <option value="Cliente">Cliente</option>
  <option value="Administrador">Administrador</option>
</select>
<input type="email" name="email" placeholder="E-mail">
<input required="" type="password" name="senha" id="senha" style="display:none;" placeholder="Senha">

  • 2

    $('[name="email"]').prop('required', true);

1 answer

1


You can add the attribute using attr and remove with removeAttr, since you’re using jQuery.

See the example below. I added an id to the email and a form tag for this example:

$("#tipo").change(function() {
  if (this.value == "Administrador") {
    $('#senha').show();
    $('#email').attr('required','required');
  } else {
    $('#senha').hide();
    $('#email').removeAttr('required');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <select name="tipo" id="tipo">
    <option value="Cliente">Cliente</option>
    <option value="Administrador">Administrador</option>
  </select>
  <br />
  <input type="email" name="email" id="email" placeholder="E-mail" >
  <br />
  <input required="" type="password" name="senha" id="senha" style="display: none;" placeholder="Senha">
  <br />
  <input type="submit" value="Clique aqui para simular o submit" />
</form>

Documentation: https://api.jquery.com/attr/

Browser other questions tagged

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