my first jQuery plugin, only seems to bind to the first form of eight forms on the page - JavaScript
[ my first jQuery plugin, only seems to bind to the first form of eight forms on the page ]
I'm writing a small jQuery plugin that binds to 8 divs on a page, each of which contains a form. There are two links for each widget that increment or decrement a field within the form and then POSTs the form. The problem is that all 16 links on the page all submit the first form on the page.
The source code is here: http://pastie.org/657045
I'm a jQuery/JS newb and figure this is probably a variable scope issue, but I've tried everything and can't get the elements to operate independently.
Answer 1
At the very beginning, you need to iterate through the results of the $(containerobj) and run the rest of the code through that, replacing each reference, like this:
jQuery.RankWidget = function(containerobj, options) {
return $(containerobj).each(function() {
var $container = $(this);
var $form = $container.find('.rank_buttons form');
var $rank_up = $container.find('.rank.up');
var $rank_down = $container.find('.rank.down');
var $value_field = $container.find('input.rank_value');
var $comment_score = $container.find('.comment_score');
var $comment_rank = $container.find('.comment_rank');
...
};
};
At the moment, you're applying all the events to all of the links, rather than scoping it to each container object in turn.
Answer 2
I solved my problem by using .click() instead of .live()
Anyone know if there is away to use .live() and get the scope for each widget correct? I even tried passing in the variable as an argument to the clickRank() function, but it was still referencing the wrong form.