Complex problem in jQuery
I have a problem that has been consuming me for days.
I have a div and the div has a style for it to be hidden ( .copy { display: none; }
).
I have a link (Add new) that when clicked, makes a clone of that div and removes the class "copy", causing the div to appear.
Inside this div, I have 4 checkbox and a text input. Clicking this checkbox, the values are displayed in this input text.
When I click once on "Add New", he makes sure, but if I click a second time on the link "Add New" it shows all the checkbox values in the second input of the div, if I click again on "Add New" he starts to put the values in the input of the third div ...
It's complicated to explain, I do not know i开发者_Go百科f I'm being clear, but put the example in jsbin http://jsbin.com/eteyu3.
See:
Click the "Add New" only once and then click the checkbox. Then click "Add New" again and see that it stops working right.
I wish he would just show the values of the div corresponding checkbox.
http://jsbin.com/eteyu3/2
I changed it this way and it works now.
jQuery(document).ready(function() {
var $current = jQuery(this);
jQuery(".add_new").bind("click", function() {
var copy = jQuery(".copy").clone().insertBefore(".copy").removeClass("none").removeClass("copy");
jQuery("input:checkbox", copy).click(function() {
var val = [];
jQuery(':checkbox:checked', copy).each(function(i) {
val[i] = jQuery(this).val();
});
jQuery(".resultfinal", copy).val ( val );
});
jQuery(".count").val( jQuery(".opt:not(.copy)").length );
});
});
While i am on it to fix this... everyone might use this: http://jsfiddle.net/c8aHb/
maybe your example is contrived but your approach seems more complex that it needs to be. Irregardless, your problem is you are re-binding the click event for all checkboxes over and over which will cause multiple events to be fired. try
unbind('click').bind('click')
where you do the click binding
You can use .parent()
to find the div containing the clicked checkbox, and then search within that parent for the textbox you're trying to populate.
jQuery($seletor + ':checkbox').click(function()
{
var val = [], $parent = jQuery(this).parent();
$parent.find(':checkbox:checked').each(function(i)
{
val[i] = jQuery(this).val();
});
$parent.find(".resultfinal").val ( val );
});
You can also use .live
instead of worrying about binding events when each checkbox is created. Your code will boil down to:
jQuery.noConflict();
jQuery(document).ready(function()
{
jQuery('div.opt :checkbox').live('click', function() {
var val = [], $parent = jQuery(this).parent();
$parent.find(':checkbox:checked').each(function(i) {
val[i] = jQuery(this).val();
});
$parent.find('.resultfinal').val(val);
});
jQuery(".add_new").bind("click", function() {
jQuery(".copy").clone().insertBefore(".copy").removeClass("none").removeClass("copy");
jQuery(".count").val( parseInt(jQuery(".count").val()) + 1 );
});
});
精彩评论