2 boxes, 2 dynamic maximums changing when one is set
I've got this code which sets dynamic maximum values for two text boxes:
var length = document.getElementById('firstBox'),
width = document.getElementById('secondBox');
max1 = 100;
min1 = 20;
max2 = 200;
min2 = 10;
length.onchange = function() {
var maxValue, minValue;
if (width.value < max1) {
maxValue = max2;
minValue = (width.value < min1) ? min1 : min2;
} else {
maxValue = max1;
minValue = min1;
}
if (this.value > maxValue) {
this.value = maxValue;
}
if (this.value < minValue) {
this.value = minValue;
}
};
width.onchange = function() {
var maxValue, minValue;
if (length.value < max1) {
maxValue = max2;
minValue = (length.value < min1) ? min1 : min2;
} else {
maxValue = max1;
minValue = min1;
}
if (this.value > maxValue) {
this.value = maxValue;
}
if (this.value < minValue) {
this.value = minValue;
}
};
It works very well, only I would like to have the maximum (max2) switch to the other box if the customer types in a value higher than the lowest maximum (max1) in that box.
Say a customer types "150" in box one, then that box automatically gets assigned max2 "200" - but what I want, is if the customer then also types "150" or any value higher than max1 in the second box, then that should become the max2, meaning the first box will be lowered from it's "150" to "100" as is the max1. And vice versa.
Hopefully that's understandable, otherwise开发者_JAVA技巧 let me know and I'll try to explain it better.
The idea is instead of holding the variables firstbox
and secondbox
to hold pointer variables to the box that conforms to max1 max1box
and the box that conforms to max2, max2box
.
In the case the logic dictates to switch maxes, you just switch the pointers around.
var max1box = document.getElementById('length'),
max2box = document.getElementById('width');
max1 = 100;
min1 = 20;
max2 = 200;
min2 = 10;
max1box.addEventListener('change',validateValues);
max2box.addEventListener('change',validateValues);
function validateValues() {
if (this == max1box && this.value > max1 && this.value > max2box.value)
{
max1box = max2box;
max2box = this;
}
if (max1box .value > max1) {
max1box .value = max1;
}
if (max1box .value < min1) {
max1box .value = min1;
}
if (max2box.value > max2) {
max2box.value = max2;
}
if (max2box.value < min2) {
max2box.value = min2;
}
}
You can see it in action here: http://jsfiddle.net/Hm2Qn/1/
The rules when to switch might not be exactly what you need but you can take it from here.
精彩评论