简体   繁体   中英

when one field is filled other fields must be required

I created a form.In that i added validations.if one field in the form is filled,all other fields must be filled or if none of the fields are filled then no need of checking validations. Iam using a method focus to add validations.once selecting a field,all fields are required validation executing.

iam using jquery-validation

 <script>

$(document).ready(function () {

    $("#myFormId").validate(
            {

            }
    );

    $('.contact1').focus(function () {
        $('.contact1').addClass("required");
    });
    $('.contact2').focus(function () {
        $('.contact2').addClass("required");
    });



});
    </script>

when i clicking on the field required is adding to field.how to remove required if no field is filled in the form

 $('#myFormId').on('change', function() { // change or input event var $inputs = $(this).find(':input:not(:submit)'); var anyInputChanged = !!$inputs.filter(function() { return this.value !== this.defaultValue; }).length; $inputs.toggleClass('required', anyInputChanged); }); 
 .required { outline: 1px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="myFormId"> <input> <input> <input type="submit"> </form> 

You could toggle required class if any input in form has no more its default value:

$('#myFormId').on('change', function() { // change or input event
  var $inputs = $(this).find(':input:not(:submit)');
  var anyInputChanged = !!$inputs.filter(function() {
    return this.value !== this.defaultValue;
  }).length;
  $inputs.toggleClass('required', anyInputChanged);
});

You're code doesn't quite match up with what you want to do, it could look more like this:

<script>

$(document).ready(function () {

    $("#myFormId").validate(
        {
            ...
        }
    );

    $('#myFormId input').on('focus keyup', function() {
        if($(this).val().length > 0){
            $('#myFormId input').attr("required",true);
        }
        else{
            $('#myFormId input').attr("required",false);
        }
    });

    });
</script>

Also, you may need to re-call the validate function on the form when you alter the attributes (but don't quote me on that).

This should be closer to what you want, but have a play around!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM