Reputation: 301
How goes it folks,
What would you say is the best way to split a percentage amongst different form inputs using Jquery? Ie.
<input type="text" value="" name="inputOne" />
<input type="text" value="" name="inputTwo" />
<input type="text" value="" name="inputThree" />
<input type="text" value="" name="inputFour" />
The idea is on keyup of each of these inputs, the value is taken--subtracted from 100% and then be divided and set as the value of the other fields.
So ultimately if input 25 as the value of Inputone the rest of the fields should then look like:
<input type="text" value="25" name="inputTwo" />
<input type="text" value="25" name="inputThree" />
<input type="text" value="25" name="inputFour" />
As always, any help is appreciated
Upvotes: 3
Views: 1628
Reputation:
Here is a dynamic solution that works based on a class with any number of divs.
$('.Maths').on('keyup', function() {
var base = parseInt($(this).val());
var count = $('.Maths').length;
var rest = (100 - base) / (count - 1);
$(this).siblings().val(rest.toString());
});
http://jsfiddle.net/scottbeeson/RMksp/
Upvotes: 1
Reputation: 55750
You can try this approach..
$('input').on('keyup', function() {
var val = this.value,
$allInputs = $('input');
if(val > 100) {
$allInputs.val(100/$allInputs.length);
}
else {
var length
$('input').not(this).val( (100-val)/ ($allInputs.length-1) ) ;
}
});
Need to add some error checks though
Upvotes: 5