Reputation: 33
I have simple
code to increment and decrement field. everything was fine but i don't know how many field I get ( it's generate by mvc) My question is how to smart bind two buttons for each field on page?
I tried to use $(this.id+"x").val(currentVal - 1)
but it's wrong way , I think.
Thanks for any suggestions
Additional:
Upvotes: 0
Views: 1841
Reputation: 1985
$(".bplus").click(function(){
var txtField = $(this).parents('tr').find('input[type="number"]')
var currentVal = parseInt(txt.val());
if (currentVal < 999)
txtField.val((currentVal || 0) + 1);
});
I put (currentVal || 0)
, that means if currentVal==NaN
, it will be replaced by 0
Upvotes: 0
Reputation: 76003
You can select elements relative to the one that has the event triggered on it:
$(".bplus").click(function() {
//find the input relative to this element
$(this).closest('td').prev().children('input').val(function (i, oldValue) {
//make sure the old value is being interpreted as an integer
oldValue = parseInt(oldValue, 10);
//if the old value is a valid integer below 999 then add one,
//otherwise return 999
return (oldValue != NaN && oldValue < 999) ? (oldValue + 1) : 999;
});
});
$(".bminus").click(function() {
//find the input relative to this element
$(this).closest('td').next().children('input').val(function (i, oldValue) {
//make sure the old value is being interpreted as an integer
oldValue = parseInt(oldValue, 10);
//if the old value is a valid integer above 0 then subtract one,
//otherwise return 0
return (oldValue != NaN && oldValue > 0) ? (oldValue - 1) : 0;
});
});
Here is a demo: http://jsfiddle.net/uSzr7/16/
Here is some documentation for ya:
.closest()
: http://api.jquery.com/closest.prev()
: http://api.jquery.com/prev.children()
: http://api.jquery.com/children.val()
: http://api.jquery.com/val (see the section on passing .val()
a function)Another way to handle the validation is to always add or subtract one but then add a change
event handler to the input
elements that checks to make sure the value is valid. This helps work with native form controls since you are using the type="number"
input tag.
Upvotes: 1