Reputation: 13
My problem is that I have a table with multiple checkboxes and few buttons. Each checkbox have some value (number). What I'm trying to achieve is to could manipulate values in all checked checkboxes using buttons. When I click on the button than values in all selected checkboxes should increase/decrease (depend from clicked button).
I have so far this:
$("input:checkbox").change(function () {
$("input:checkbox").each(function () {
if ($(this).is(":checked")) {
var count = 0,
newVal = parseInt($(this).val());
$("#increase").click(function () {
for (i = 0; i < 1; i++) {
count += 1;
if (newVal >= 90) {
newVal = 100;
$("#increase").prop('disabled', true);
} else {
newVal += 10;
$("#increase").prop('disabled', false);
}
console.log(newVal)
}
});
}
});
});
I don't know how to update old values with those new (increased).
Upvotes: 1
Views: 1020
Reputation: 144689
For increasing and decreasing values, you can use jQuery val
method's callback function.
$("#increase, #decrease").click(function() {
var num = this.id === 'increase' ? 10 : -10;
$('input[type=checkbox]').val(function(_, value){
return +value + num;
});
});
Regarding disabling the buttons: Since you have 1 increase/decrease button for all the elements you can't properly disable the button unless you have 1 button for each checkbox. For example one new value is 88, and another 100, I'm not sure in which case the button should be disabled/re-enabled.
Update: If you only want to increase/decrease values of the checked checkboxes, you can use :checked
selector:
$("#increase, #decrease").click(function () {
var num = this.id === 'increase' ? 10 : -10;
$('input[type=checkbox]:checked').val(function (i, value) {
var newVal = +value + num;
if (newVal > 100) newVal = 100;
else if (newVal < 0) newVal = 0;
return newVal;
});
});
Upvotes: 1
Reputation: 4398
You shouldn't need the first change
event. This will run whenever you actually change the value of one of your check boxes. What you want is to bind the event to the click action of your button. So you want something like:
$("#increase").click(function() {
$("input[type=checkbox]:checked").each(function(idx, input) {
var val = $(this).val();
if (val >= 90) {
val = 100;
$("#increase").prop('disabled', true);
} else {
val += 10;
$("#increase").prop('disabled', false);
}
});
});
This should do what you're after
Upvotes: 0
Reputation: 104775
Here's what I came up with, hope it helps:
$("#increase").click(function() {
$("input[type='checkbox']").each(function() {
if (this.checked) {
var newVal = parseInt(this.value);
if (this.value >= 90) {
newVal = 100;
$("#increase").prop('disabled', true);
} else {
//do other stuff
newVal += 10;
$("#increase").prop('disabled', false);
}
console.log(newVal);
}
});
});
Fiddle: http://jsfiddle.net/5Et7g/2/
Upvotes: 0