Gaby
Gaby

Reputation: 55

Remove 'required' from checkbox when an input is filled with jQuery Validate plugin

So im doing a contact form with several text inputs and checkboxes and validating with the jQuery Validate plugin, and what i want to achieve is this:

screenshot of my contact form

When the text input is filled, the 'required' attribute from the rules of the plugin aplied on the checkboxes get removed.

This is my HTML(inside a bootstrap modal:

<div id="invitoUno" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header" style="height: 0; border-bottom: none;">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="row form-invito">
                    <div class="col-12">
                        <form method="post" action="solicitudinvito.php" id="invitoform" name="invitoform">
                            <h6>Nombre completo:</h6>
                            <div class='cb-input'>
                                <input id='nombre' type="text" name="nombre" placeholder="" required />
                            </div>
                            <div class='cb-input'>
                                <input type="text" value="Fam. de Luis Arturo Garza Bassoco" id="persona" name="persona" hidden>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-12">
                                    <h6>Celular:</h6>
                                    <div class='cb-input'>
                                        <input id='celular' type="text" name="celular" placeholder="" required />
                                    </div>
                                </div>
                                <div class="col-sm-6 col-12">
                                    <h6>Teléfono de casa (opcional):</h6>
                                    <div class='cb-input'>
                                        <input id='telcasa' type="text" name="telcasa" placeholder="" />
                                    </div>
                                </div>
                            </div>
                                    <h6>¿Requieres de recibo deducible de impuestos?:
                                <label style="padding-left: 20px;">Sí</label>

                                <input type="checkbox" class="factura option-input checkbox" name="factura" value="Requiere factura" required />
                                <!--   -->
                                <label style="padding-left: 20px;">No</label>

                                <input type="checkbox" class="factura option-input checkbox" name="factura" value="No requiere factura" placeholder="" required />
                                <!--   -->
                            </h6>
                            <br>
                            <h4 style="padding-bottom:5px;">deseo invitarle la despensa a:</h4>

                            <div class="row">
                                <div class="col-sm-2 col-12">
                                    <span style="color:#5C5B5F; font-family:'PT Sans', sans-serif;">1 familia</span><br>
                                    <span class="cantidad">$160.00</span>
                                    <input type="checkbox" class="familia option-input checkbox" style="top:10%;" name="familia" value="Apoya una familia = $160.00" placeholder="" required />
                                </div>
                                <div class="col-sm-2 col-12">
                                    <span style="color:#5C5B5F; font-family:'PT Sans', sans-serif;">2 familias</span><br>
                                    <span class="cantidad">$320.00</span>
                                    <input type="checkbox" class="familia option-input checkbox" style="top:10%;" name="familia" value="Apoya dos familias = $320.00" placeholder="" required />
                                </div>
                                <div class="col-sm-2 col-12">
                                    <h6 style="color:#FFBA00;">Otra cantidad:</h6>
                                </div>
                                <div class="col-sm-6 col-12">
                                    <div class='cb-input' style="margin-top: -10px;">
                                        <input id='otrafamilia' type="text" name="familia" placeholder="$" />
                                    </div>
                                </div>
                            </div>
                            <br>
                            <h4 style="padding-bottom:5px;">Aportación empresa mensual:</h4>

                            <div class="row">
                                <div class="col-sm-4 col-12">
                                    <span class="cantidad">$1,000.00</span>
                                    <input type="checkbox" class="aportacion option-input checkbox" style="top:10%;" name="empresa" value="Aportacion mensual de $1000.00" placeholder="" />
                                </div>
                                <div class="col-sm-2 col-12">
                                    <h6 style="color:#FFBA00;">Otra cantidad:</h6>
                                </div>
                                <div class="col-sm-6 col-12">
                                    <div class='cb-input' style="margin-top: -10px;">
                                        <input id='empresaotra' type="text" name="empresa" placeholder="$" />
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 text-center" style="box-shadow: none; margin-bottom: 0px;">
                                <label class="acepto" style="padding-left: 20px;">Acepto el compromiso con Banco de Alimentos de Los Mochis I.A.P.</label>
                                <input type="checkbox" class="option-input checkbox" name="compromiso" value="Acepto el compromiso con Banco de Alimentos de Los Mochis I.A.P." required />
                            </div>
                            <div class="col-12 text-center" style="padding-top: 30px; padding-bottom: 30px;">
                                <button class="btn-amarillo" type="submit" id="submit">envíar</button>
                            </div>
                        </form>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

and this are the rules:

<script type="text/javascript">
    $(document).ready(function() {
        $('#celular').mask('(000) 000-0000');
        $('.success').fadeOut(0);
        var v = $("#invitoform").validate({
            rules: {
                nombre: {
                    required: true
                },
                celular: {
                    required: true
                },
                factura: {
                    required: true, 
                    minlength: 1 
                },
                familia: {
                    required: true
                },
                empresa: {
                    required: true
                },
                compromiso: {
                    required: true
                }
            },
            messages: {
                nombre: {
                    required: "Debes escribir tu(s) nombre(s) y apellido(s).",
                },
                celular: {
                    required: "Debes de escribir tu número de teléfono.",
                    minlength: "El número que ingresaste no es válido."
                },
                factura: {
                    required: "Debes elegir una opción."
                },
                familia: {
                    required: "Debes de elegir una opción o escribir una cantidad."
                },
                empresa: {
                    required: "Debes de elegir una opción o escribir una cantidad."
                },
                compromiso: {
                    required: "Necesitas aceptar tu compromiso con nosotros antes de continuar."
                }
            }

        })
    });
</script>

Despite they have the same name (the 2 checkboxes and text input) the rule "required" doesn't seem to work because when i fill the input one of the checkboxes are still needed to continue.

Upvotes: 1

Views: 999

Answers (1)

Sparky
Sparky

Reputation: 98718

"Despite they have the same name (the 2 checkboxes and text input) the rule "required" doesn't seem to work because when i fill the input one of the checkboxes are still needed to continue."

What? You put the same name on checkboxes and text elements? That does not even make any sense and it will just ignore the second instance.

First, fix the name attributes so they are unique. Only that grouping of checkboxes can have the same name.

Second, if you want to change rules based on some dynamic condition, then you would put conditional functions in place of rule declarations.

rules: {
    ....
    empresa_checkbox: {
        required: {
            depends: function() {
                // checkbox only required when text field is empty
                return $('input[name="empresa_text"]').is(':blank');
            }
        }
    },
    empresa_text: {
        required: {
            depends: function() {
                // text box only required when checkbox is unchecked
                return $('input[name="empresa_checkbox"]').is(':unchecked');
            }
        }
    },
    ....             
},

And finally, you do NOT need the HTML5 required attribute on any elements since you're declaring your rules within the .validate() method. You should remove those permanently to ensure they don't interfere or cause confusion.

Upvotes: 1

Related Questions