简体   繁体   中英

jQuery Validate - Multiple Input fields - some are required

I have the following problem:

I got a form with 3 input fields type number. I want at all time that only 2 to be required. So if Input A and input B are filled in input C is disabled. But when the user clears input A, input C must be available. etc.. so 2 must be filled in, there is no matter which two !

I'm making a small application for the "theory of pythagoras" where you can fill in two sides. Doesn't matter which 2 sides.

<div class="selector">
    <input type="number" placeholder="A" name="A" id="A">
    <input type="number" placeholder="B" name="B" id="B">
    <input type="number" placeholder="C" name="C" id="C">
</div>

jQuery Validation:

$(".selector").validate({
  rules: {
    // simple rule, converted to {required:true}
    A: "required",
    B: "required",
    C: "required"
  }
});

who can help me !

I have built upon the answer of sumeet . This code should be fully functional:

 $(document).on("change",".selector input",function(e){ var emptyFields = Array(); $(".selector input").each(function(i){ if(!this.value) { emptyFields.push(this.getAttribute("id")); } }); if(emptyFields.length === 1) { $("#"+emptyFields[0]).attr('readonly', true); } else { emptyFields.forEach(function(id) { $("#"+id).attr('readonly', false) ; }); } }); 
 <div class="selector"> <input type="number" placeholder="A" name="A" id="A"> <input type="number" placeholder="B" name="B" id="B"> <input type="number" placeholder="C" name="C" id="C"> </div> 

There are two possible ways meet your requirement depending on what technique you are using. if you are calculating some value, you might need to have a function let say it calc().

  1. first and the simpler way is to call it on "click" event of some element. In this case, instead of assigning required attribute to each element, just check before the calculation how many filled values are there.

  2. The second point where calc() can be called is on change() or on keypress event of each element with some specific class.

This function can be used in both mentioned scenarios

function validator(){
    var fields = $(".selector").children();
    var lv,counter=0;
    for(lv=0;lv<fields.length;lv++){
        if($(ss[lv]).val()==""){
            counter++;
        }
    }
    return counter>=2;
}

And here are some sample usages:

for first case:

$("#btnCalc").on("click",function(){
    if(!validator()){
        DO YOUR CALC
    }else{
        alert("Atleast two fields are required to be filled");
    }
    return false;
});

for second case:

$(".selector").change(function(){
    if(!validator()){
        //DO YOUR CALC
    }
    else{
        errorDiv.val="Atleast two fields are required to be filled"; //pseudo code :)
    }
    //console.log(fields.length);
    return false;
});

This is a quick response and code can be optimized using global variables

You can add / remove validation using below code -

put B as required because this will be available always

$(".selector").validate({
  rules: {
    // simple rule, converted to {required:true}
    B: "required"
  }
});

now add / remove required validation as per value in A

$('input[name="A"]').keyup(function(){
   if($(this).val().trim()=="")
  {
    $(this).rules("remove", "required");
    $('input[name="C"]').rules("add", "required");
    $('input[name="C"]').removeProp('disabled');
  }
  else
  {
    $(this).rules("add", "required");
    $('input[name="C"]').rules("remove", "required");
    $('input[name="C"]').prop('disabled',true);
  }
}):
$(document).on("change",".selector input",function(e){
    $(".selector input").attr('readonly', false) ; 
    var flag = 0;
    var id;
    debugger;
    $(".selector input").each(function(i){

        if(this.value!="")
        {
            flag++;
        }
        else
        {            
            id  = this.getAttribute("id");
        }    

    });

    if(flag == 2)
        $("#"+id).attr('readonly', true) ;
    else
        $("#"+id).attr('readonly', false) ;

});

I have updated the link just check - > http://jsfiddle.net/sumeetp1991/dvdvye4p/3/

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