jquery validate total percentange of two inputs not greater than 100%

白昼怎懂夜的黑 提交于 2019-12-12 02:57:09

问题


I'm out of idea how to set validation rule to my form. I have two fields for input of numbers which represent percentage and I wanna to set the rule which checks if total or sum of this two field is not greater than 100.

So far i added rule that checks if number entered in one of the fields isn't greater than 100 but that's not my final solution. I need it to forbid user for entering in example in both fields 100, or 90 and limit only so the total sum is equal to 100. for example he can input in one field 60 and in other 40.

I have my situation in jsfiddle: http://jsfiddle.net/te956/1/

and here is html code:

<form class="form-horizontal" id="whereEntry" method='post' action='/start/'>
<fieldset>

    <div class="control-group">
         <div class="controls controls-row">
                <input type="text" class="span2 register_input" id="income"    name="income" placeholder="% of income">
         </div>
    </div> 

    <div class="control-group">
         <div class="controls controls-row">
                <input type="text" class="span2 register_input" id="income_2" name="income_2" placeholder="% of income">
         </div>
    </div>

<div class="control-group">
    <label class="control-label" for="input01"></label>
        <div class="controls text-center">
            <button type="submit" id="btn_next" class="btn btn-primary btn-large">Next</button>
        </div>
</div>



  </fieldset>
</form>

and script looks like this:

$(document).ready(function(){

 $('#whereEntry').validate({
  rules: {
    income: {
        required: true,
        number: true,
        min: 0,
       max: 100,
        },
income_2: {
    required: true,
    number: true,
    min: 0,
    max: 100,
        }    
 },

  highlight: function(element) {
    $(element).closest('.control-group').removeClass('success').addClass('error');
  },
      success: function(element) {
    element
    .text('OK!').addClass('valid')
    .closest('.control-group').removeClass('error').addClass('success');
  }       
    });

}); // end document.ready

I would be grateful if you could update my jsfiddle: http://jsfiddle.net/te956/1/


回答1:


After entering a value to either one of the input fields, you could:

  • check what the value was (X)
  • substract it from the total value (100% - X)
  • set the remaining as a max value for the other input field (rules > income > max: X)



回答2:


I realize this is an older question but I was having the same problem and searched everywhere for a valid answer. I was unable to get any answer I saw working so I went about it a different way. Here is my solution to this.

 <div class="col-lg-4">
      <div class="card-box clearfix parentDiv">
        <form id="liability-form" action="." method="post">
          <input type="hidden" name="action" value="update_liability">
          <input id="total-slide" type="hidden" name="total_slide" value="">
          <input id="percent100" type="hidden" name="percent_100" value="100">
          <div class="slider-container">
            <input id="slider9" class="slider-total" type="text" name="liability[9]" data-slider-min="0" data-slider-max="100" data-slider-step="10" data-slider-value="100" />
            <span id="9label" class="slider-name">Kevin Alley: <span id="9val">100</span>%</span>
          </div>
          <div class="slider-container">
            <input id="slider10" class="slider-total" type="text" name="liability[10]" data-slider-min="0" data-slider-max="100" data-slider-step="10" data-slider-value="0" />
            <span id="10label" class="slider-name">Briana Alley: <span id="10val">0</span>%</span>
          </div>
          <div class="errorTxt"></div>
          <button type="submit" class="btn btn-gray pull-left m-t-30">Update Liabilities</button>
        </form>
      </div>
    </div>
    <!-- end col -->

Here is the javascript I used

$("#slider9").slider();
 $("#slider9").on("slide", function(slideEvt) {
   $("#9val").text(slideEvt.value);
   var total = 0;
   $('.slider-container').each(function() {
     var row = $(this).find("input[type=text]").val();
     //var row = $(this).val();
     total += parseFloat(row);
     $("#total-slide").val(total);
   });
   var total = 0;

 });
 $("#slider10").slider();
 $("#slider10").on("slide", function(slideEvt) {
   $("#10val").text(slideEvt.value);
   var total = 0;
   $('.slider-container').each(function() {
     var row = $(this).find("input[type=text]").val();
     //var row = $(this).val();
     total += parseFloat(row);
     $("#total-slide").val(total);
   });
   var total = 0;
 });

 $("#liability-form").validate({
    ignore: [],
    rules: {
        total_slide: {
            equalTo: '#percent100'
        }
    },
    messages:{
        total_slide:{
            equalTo: 'Liability for all users must equal 100%'
        }
    },
    errorElement : 'div',
    errorLabelContainer: '.errorTxt'
});

https://jsfiddle.net/kevin3954/x9q0456m/1/




回答3:


My input form with dynamic fields,

<div class="col-md-9">
    <input type="text" class="form-control"
        name="nominees[0].nomineeAmnt" id="nomineeAmnt1">
</div>

<div class="col-md-9">
    <input type="text" class="form-control"
        name="nominees[1].nomineeAmnt" id="nomineeAmnt2">
</div>

<div class="col-md-9">
    <input type="text" class="form-control"
        name="institutes[0].instituteAmnt" id="instituteAmnt1">
</div>

<div class="col-md-9">
    <input type="text" class="form-control"
        name="institutes[1].instituteAmnt" id="instituteAmnt2">
</div>

<div class="col-md-9 col-md-offset-3">
    <input type="hidden" class="form-control" name="totalPercent"
        id="totalPercent">
</div>

We can add jQuery validation function to calculate total percentage for the fields having id starting with same name,

jQuery.validator.addMethod("totalPercent", function (value, element) {
    var total = 0;
    $("[id^=nomineeAmnt]").each(function(){
        if(parseInt($(this).val()) > 0){
            total += parseInt($(this).val());
        }
    });

    $("[id^=instituteAmnt]").each(function(){
        if(parseInt($(this).val()) > 0){
            total += parseInt($(this).val());
        }
    });

    return total === 100;
}, function(params, element) {
  return 'Total amount should be 100%.'
});

And then just use the function,

$("#nomineeForm").validate({
    ignore: [],
    rules:{
        totalPercent:{
            totalPercent: true
        }
    }
});


来源:https://stackoverflow.com/questions/16940336/jquery-validate-total-percentange-of-two-inputs-not-greater-than-100

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!