将三个输入数字的最大值设置在一起

时间:2018-04-04 07:08:17

标签: javascript jquery html input numbers

我有三个输入数字:



<input min="0" name="cat1" step="1" type="number" max="50" value="0" />            
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />
&#13;
&#13;
&#13;

目前最大值为50.我希望所有三个的最大值一起为50。

如何使用javascript或jquery解决此问题?

5 个答案:

答案 0 :(得分:2)

此方法将其他输入相加,如果总和+当前值大于最大值,则会更改当前输入的值以适应最大值。

例如,尝试在输入框中输入30,5,20。

var max = 50;
var $inputs = $('input');

function sumInputs($inputs) {
  var sum = 0;
  
  $inputs.each(function() {
    sum += parseInt($(this).val(), 0);
  });

  return sum;
}

$inputs.on('input', function(e) {
  var $this = $(this);
  var sum = sumInputs($inputs.not(function(i, el) {
    return el === e.target;
  }));
  var value = parseInt($this.val(), 10) || 0;
  if(sum + value > max) $this.val(max - sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="0" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />

答案 1 :(得分:1)

希望你有这样的期待。 尝试使用此代码。 它将检查三个字段的总和,并检查它是否大于50。

&#13;
&#13;
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Location } from '@angular/common';
import { ImageService } from '../metric-details/shared/image.service';
import { LibraryService } from '../library.service';
import { Library } from '../library';
import { GraphService } from '../graph.service';


@Component({
  selector: 'app-metric-view',
  templateUrl: './metric-view.component.html',
  styleUrls: ['./metric-view.component.css']
})
export class MetricViewComponent implements OnInit {
image: any
graph: any
library: Library;
visibleImages: any[] = [];


  constructor(private imageService: ImageService, private libraryService:LibraryService, private graphService:GraphService, private location: Location, private route: ActivatedRoute, private router: Router) {
    this.visibleImages = this.imageService.getImages();
   }

  ngOnInit() {
    this.getLibrary();

    this.image = this.imageService.getImages(
      +this.route.snapshot.params['id'])

    this.graph = this.graphService.getGraph(
      +this.route.snapshot.params['id'])
  }

  getLibrary(): void{
    const id = +this.route.snapshot.paramMap.get('id');
    this.libraryService.getLibrary(id)
      .subscribe(library => this.library = library);
  }

}
&#13;
$(":input").bind('keyup mouseup', function () {          

  var cat1=$("#cat1").val();
  var cat2=$("#cat2").val();
  var cat3=$("#cat3").val();
  var total=parseInt(cat1) + parseInt(cat2) + parseInt(cat3);
 
  if(total>50) {
    alert("it exceeds 50");
    return false;
  }
  
});
&#13;
&#13;
&#13;

答案 2 :(得分:1)

这将确保总和不超过50.如果新值使总数超过限制,则另外两个将平均降低以强制执行总计= 50的规则。

注意

let share2 = Math.min(Math.floor(excessValue / 2), elmt2Value) which ensures

确保我们不会从其中一个输入中删除多于其值的内容。

<input min="0" name="cat1" id="cat1" step="1" type="number" max="50" value="0" onchange="valueChanged('cat1')" />            
<input min="0" name="cat2" id="cat2" step="1" type="number" max="50" value="0" onchange="valueChanged('cat2')" />
<input min="0" name="cat3" id="cat3" step="1" type="number" max="50" value="0" onchange="valueChanged('cat3')" />

<script>
     function valueChanged(changedElmtId) {

        // Retrieve all input, the one changed and the other 2
        let elmt2Id = "cat2", elmt3Id = "cat3"
        if ( changedElmtId === elmt2Id ) {
            elmt2Id = "cat1"
        }
        else if ( changedElmtId === elmt3Id ) {
            elmt3Id = "cat1"
        }

        let changedElmt = document.querySelector("#" + changedElmtId)
        let elmt2 = document.querySelector("#" + elmt2Id)
        let elmt3 = document.querySelector("#" + elmt3Id)

        let elmt2Value = parseInt(elmt2.value)
        let elmt3Value = parseInt(elmt3.value)

        // Check if any action is needed
        let totalValue = parseInt(changedElmt.value) + elmt2Value + elmt3Value
        if ( isNaN(totalValue) || totalValue <= 50 )
            return

        // Measure excess then split in 2
        let excessValue = totalValue - 50
        let share2 = Math.min(Math.floor(excessValue / 2), elmt2Value)
        let share3 = excessValue - share2

        console.log("Current:", " " + elmt2Id + ": ", share2, " " + elmt3Id + ": ", share3)
        console.log("Total:", totalValue, " Excess: ", excessValue, " " + elmt2Id + ": ", share2, " " + elmt3Id + ": ", share3)


        elmt2.value = elmt2Value - share2
        elmt3.value = elmt3Value - share3

     }
</script>

答案 3 :(得分:0)

我不知道我的解决方案有多优,但它有效。也涵盖了一些边缘案例。

&#13;
&#13;
let inputs = document.querySelectorAll('input');
const max = inputs[0].getAttribute("max");
let value;
inputs.forEach((input, i) => {
  input.addEventListener('change',(e) =>handleChange(e)); // adding change event
  input.addEventListener('blur',(e) =>handleChange(e)); //adding a blur eventto prevent direct  typing of input larger than max
})

const handleChange = (e) =>{  
  if(e.target.value > max - value){
    e.target.value = max-value; //setting max value possible if input value is greater than max
    return;
  }else{
    value = 0;
    inputs.forEach( input => {
      value+=parseInt(input.value); //calculating value to negate from max
    });
    inputs.forEach( input => {
      if(max-value > 0){
       input.setAttribute("max", max-value);  //setting max value on every input
      }    
    }); 
  }     
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input min="0" name="cat1" step="1" type="number" max="50" value="0" />            
  <input min="0" name="cat2" step="1" type="number" max="50" value="0" />
  <input min="0" name="cat3" step="1" type="number" max="50" value="0" />
</body>
</html>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

我希望这对你来说很容易小而快,因为表格中的输入数量较少。

&#13;
&#13;
        |Autoplus.txt|{Tue Apr 03 17:20:00 IST 2018}|
        |Autoplus6.txt|{Tue Apr 03 18:13:00 IST 2018}|
&#13;
$(function(){
  $('input[type=number]').attr('max', '50')
})
&#13;
&#13;
&#13;