Search code examples
javascriptjqueryincrementon-the-flydecrement

Creating buttons for textbox and assigning click functions on the fly in JQuery


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();

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();
    });