使复选框的行为类似于可复制输入字段中的单选按钮

我正在创建一个包含复选框的可复制div,在原始输入集上,复选框就像单选按钮一样,但是当复制它时,它仍然只能在第一个而不是第二个上工作。

同样在提交时,它只在控制台中返回原始表单的一个值,但对于任何重复项都没有值。

任何帮助非常感谢。

JS小提琴: http : //jsfiddle.net/dawidvdh/EEd7c/

jQuery的:

//Clone Tracking var g_counter = 1; var d_counter = 1; var dependant = ["dependant"]; var group; //Clone Tracking //General Variables var relation_input_groups = ["relation-group-1"]; //General Variables //Generate variables var relation_fields=[0]; var relation_input =""+ "" + ""+ "" + ""+ "" + ""+ "" + ""+ "" + ""+ "" + ""+ "" + ""+ ""; //Generate variables jQuery(document).ready(function(e) { //populate jquery generated fields jQuery(relation_fields).each(function() { jQuery(relation_input).appendTo('#relation-group-1'); }); //populate jquery generated fields //Cloning Function jQuery('#clone').click(function() { clone_dependant(); }); function clone_dependant() { // Store the value of the previous Id to insert the cloned div.. var oldId = g_counter; g_counter++; currentdep ='dependant-'+g_counter; // Clone the Dependant Div and set a new id var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter); var relation_newDiv = 'relation-group-'+ g_counter; // Find div's inside the cloned object and set a new id's $clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter ); // You don't need to Loop thru the inputs to set the value $clonedDiv.find('input').val(''); $clonedDiv.find('input:checkbox').removeAttr('checked'); // Insert the cloned object $clonedDiv.insertAfter("#dependant-" + oldId); relation_input_groups.push(relation_newDiv); } //Cloning Function //Validation //submit function var $unique = $('input[type="checkbox"]'); $unique.click(function() { $unique.removeAttr('checked'); $(this).attr('checked', true); }); var result = {}; var dependants; var dep_counter = 0; jQuery('#submit').click(function() { jQuery('.dependant').each(function(k, v) { dep_counter++ dependants = {}; result['dependant'+dep_counter] = [dependants]; dependants['relationship'] = $(v).find('.relationship:checked').val(); }); var jsonData = JSON.stringify(result); console.log(jsonData); }); }); 

和HTML:

 
relationship:

提前致谢 :)

它不起作用的原因是您没有将click事件附加到新的克隆元素。

 $(document).on("click", 'input[type="checkbox"]', function() { jQuery(this).siblings(":checked").removeAttr('checked'); }); 

见: http : //jsfiddle.net/EEd7c/1/

 var $unique = $('input[type="checkbox"]'); $unique.live("click", function() { $(this).siblings().removeAttr('checked'); $(this).attr('checked', true); }); 

然而Live被弃用了……

要么

 $(document).on("click", 'input[type="checkbox"]', function() { $(this).siblings().removeAttr('checked'); $(this).attr('checked', true); }); 
 var $unique = $('input[type="checkbox"]'); $unique.live('click',function() { $(this).closest('div').find('input[type="checkbox"]').removeAttr('checked'); $(this).attr('checked', true); }); 

使用live将事件处理程序注册到动态创建的元素。 $ unique变量仅包含初始的复选框集。