maksim09
maksim09

Reputation: 33

Jquery increment and decrement for dynamic generated field

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:

  1. I can't use Jquery Mobile range input.
  2. Text box "Text Pin #4" must be allways focused.
  3. All buttons must be possible to click on Mobile device.

Upvotes: 0

Views: 1841

Answers (2)

Tronix117
Tronix117

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

Jasper
Jasper

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:

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

Related Questions