Add and remove required Jquery

Asked

Viewed 3,284 times

1

I have a radio button question:

<div class="row">
    <div class="col-lg-1">
        <div class="radio">
            <label>
                <input type="radio" name="dirar" value="1">
                Sim
            </label>
        </div>
    </div>
    <div class="col-lg-2">
        <div class="radio">
            <label>
                <input type="radio" name="dirar" value="0">
                Não
            </label>
        </div>
    </div>
    // Validação de erro caso não tenha selecionado uma opção msg = "Campo Obrigatório"
    <div class="col-lg-3">
        <label id="dirar-error" class="input-error" for="dirar" style="border: none; color: red;"></label>
    </div>
</div>

If name="dirar" is selected '0' = não, I need a validation that adds required="required" to another issue that is below:

<div class="row">
    <div class="col-lg-1">
        <div class="radio">
            <label>
                <input type="radio" name="isubrar" value="1">
                Sim
            </label>
        </div>
    </div>
    <div class="col-lg-2">
        <div class="radio">
            <label>
                <input type="radio" name="isubrar" value="0">
                Não
            </label>
        </div>
    </div>
</div>

In short, if name="dirar" for '0' = Não the second radio button name="isubrar" becomes a mandatory field or name="dirar"for '1' = Sim name="isubrar"will not be a mandatory field.

  • What have you tried? Received some error?

1 answer

0


Follows a functional implementation:

$(":radio[name='dirar']").change(function(){
  if($(this).val() === "0") {
    $(":radio[name='isubrar']").attr("required", "required");
  } else {
    $(":radio[name='isubrar']").removeAttr("required");
  }
  
  console.log($(":radio[name='isubrar']").attr("required"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <div class="col-lg-1">
        <div class="radio">
            <label>
                <input type="radio" name="dirar" value="1">
                Sim
            </label>
        </div>
    </div>
    <div class="col-lg-2">
        <div class="radio">
            <label>
                <input type="radio" name="dirar" value="0">
                Não
            </label>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-1">
        <div class="radio">
            <label>
                <input type="radio" name="isubrar" value="1">
                Sim
            </label>
        </div>
    </div>
    <div class="col-lg-2">
        <div class="radio">
            <label>
                <input type="radio" name="isubrar" value="0">
                Não
            </label>
        </div>
    </div>
</div>

  • It worked Perfectly @Marcell_alves, Thank you!

Browser other questions tagged

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