最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set max value based on another input - Stack Overflow

programmeradmin4浏览0评论

I need to set a max value of an input based on the value of another input.

I will have two inputs, input x and input y, a user inputs a value in each but the value for y can be no more than 80% of the value of x, so I want a max value on input y so you can't go over 80% of input x.

so if someone puts 100 in input x and tries to put 90 in input y, input y would change to be 80 because that would be the max.

I intend to use javascript and HTML to achieve this.

I need to set a max value of an input based on the value of another input.

I will have two inputs, input x and input y, a user inputs a value in each but the value for y can be no more than 80% of the value of x, so I want a max value on input y so you can't go over 80% of input x.

so if someone puts 100 in input x and tries to put 90 in input y, input y would change to be 80 because that would be the max.

I intend to use javascript and HTML to achieve this.

Share Improve this question asked Mar 23, 2016 at 15:05 Louis DownLouis Down 511 silver badge8 bronze badges 2
  • nice idea. do you have some code to show? – Nina Scholz Commented Mar 23, 2016 at 15:07
  • I'm afraid I don't, I've looked around on this all day to find a starting point and I can't find anything – Louis Down Commented Mar 23, 2016 at 15:12
Add a ment  | 

3 Answers 3

Reset to default 3

I suggest monitoring the input using the onchange event of both fields and limiting the value using Math.min(...)

Here is a snippet:

var elX = document.getElementById("X");
var elY = document.getElementById("Y");

function limit() {
	elY.value=Math.min(Math.round(elX.value*.8),elY.value);
}

elX.onchange=limit;
elY.onchange=limit;
<input type="number" id="X" value="0"><br>
<input type="number" id="Y" value="0">

Here is a simple solution using JQuery and 2 simple input fields. It pretty much does what you want -> JSFiddle

Related HTML:

<input type="number"id="x">  
<input type="number" id="y">

Related JS:

(function(){
$("#y").on("change", function(e){
    var x = $("#x").val()
  if($(this).val() > (x*80)/100){
    $(this).val(((x*80)/100));
    alert("field Y cannot excede 80% of field X")
  }
})
}())

If I understand right:

The input is like something this:

<input type="number" id="Y" max="numberHere">

You can do it like this:

var temp = document.getElementById("Y");
var maxValue = document.getElementById("X").value * 0.8;
temp.setAttribute("max",maxValue); // set a new value;
发布评论

评论列表(0)

  1. 暂无评论