Question

I have the following code to create two buttons (one on the left one on the right) for each texbox on the page. Idea is to make an increment/decrement textbox. Code works fine with one textbox but with 2 or more every button increment/decrements all textboxes.

Any idea how to create buttons on the fly and attach them to a textbox for increment/decrement?

jQuery.fn.incrementer =  function() {
    this.val(0);
    this.before("<input class='incrementer_minus' type='button' value=' - '/>");        
    var myobj = this;
    $(".incrementer_minus").live('click', function(){
        $(myobj).val(parseInt(JQ(myobj).val()) - 1);
    });
    this.after("<input class='incrementer_plus' type='button' value=' + '/>");
    $(".incrementer_plus").live('click', function(){
        $(myobj).val(parseInt(JQ(myobj).val()) + 1);
    });
}

JQ("#increment").incrementer();
JQ("#increment2").incrementer();
Was it helpful?

Solution

You are associating the click event with every instance of incrementer_minus and incrementer_plus when you do:

$(".incrementer_plus").live('click'...

You instead need to just attach the event to the specific one that was just created.

I changed your code to do so, and I also used bind instead of live, since you just don't need live.

I also changed JQ to jQuery for my convenience. You can change it back.

Test it out: http://jsfiddle.net/mAsr9/

jQuery.fn.incrementer =  function() {
    var myobj = this;
    this.val(0);

      // Create new element, and insert before 'this'
    jQuery("<input class='incrementer_minus' type='button' value=' - '/>").insertBefore(this)

           // Then bind the click event to that new element
        .bind('click', function(){
            $(myobj).val(parseInt(jQuery(myobj).val()) - 1);
        });

      // Create new element, and insert after 'this'
    jQuery("<input class='incrementer_plus' type='button' value=' + '/>").insertAfter(this)

          // Then bind the click event to that new element
        .bind('click', function(){
            $(myobj).val(parseInt(jQuery(myobj).val()) + 1);
        });
}

$(function() {
    jQuery("#increment").incrementer();
    jQuery("#increment2").incrementer();
});

OTHER TIPS

Have a look at the jQuery Increment plugin: http://sean-o.com/increment

I created it for just such a use, hopefully it can (still?) be of help to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top