views:

31

answers:

2

Hello, 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();
A: 
Kai
yes there are many plugins out there for spinners, the point is I want to learn how to do such thing. I mean creating elements on the fly and doing this kind of stuff. Still thanks for your help :)
Ergec
+1  A: 

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();
});
patrick dw
.before() and .insertBefore() . Now I got it. I need to study more :)
Ergec
@Ergec - Yes, those clever jQuery folks gave us two methods that do the same thing, only they allow us to swap the order of the inserted element and the target so that we can perform the proper chaining. An alternative would have been to create your new element first and store it in a variable. `var $minusInput = $('<input.../>');` Then do `this.before($minusInput);` and `$minusInput.bind(func...);`
patrick dw
@patric - thanks a lot patric
Ergec