2012-09-05 37 views
0

我想將現有表單複製到另一個表單。我發現這個question其正常投入工作,但它拋出一個錯誤在我的複選框jQuery - 將表單複製到相同的表單

我使用jQuery的功能(from)是

(function($) { 
    $.fn.copyNamedTo = function(other) { 
     return this.each(function() { 
      $(':input[name]', this).each(function() { 
       $('[name=' + $(this).attr('name') +']', other).val($(this).val()) 
      }) 
     }) 
    } 
}(jQuery)); 

的錯誤是:

Uncaught Error: Syntax error, unrecognized expression: [name=cartype[]] 

的複選框按如下方式排列:

<input type="checkbox" name="cartype[]" id="cartype_10" value="10">4x4 
<input type="checkbox" name="cartype[]" id="cartype_11" value="11">Saloon 

我預計這是由於名稱中的[],但無法弄清楚如何處理它。

回答

1

你必須得到\\[\\](如佈局here)替換你的名字[],因爲(你知道)他們在jQuery選擇器中有特殊的含義。

$('[name=' + $(this).attr('name').replace(/([\[\]])/g, '\\\\$1') +']', other).val($(this).val()) 

注意,在技術上你也應該有形式$('[name="val"]')(注意屬性值周圍的引號)的選擇。 jQuery對此似乎一直很寬容,但它符合the docs

要指定複選框和單選按鈕,您需要設置它們的checked屬性,而不是更改該值。你可以改變你的功能,

$.fn.copyNamedTo = function(other) { 
    return this.each(function() { 
     $(':input[name]', this).each(function() { 
      var target = $('[name=' + $(this).attr('name').replace(/([\[\]])/g, '\\\\$1') +']', other); 

      // Radios have the same name as each other, so filter based on value 
      // Checkboxes are in the same boat here due to the naming conventions shown in the OP. 
      if ($(this).is(':checkbox, :radio')) { 
       target.filter('[value="' + this.value + '"]').prop('checked', this.checked); 
      } else { 
       target.val($(this).val()); 
      } 
     }) 
    }) 
} 
+0

這工作,因爲它沒有錯誤。但是沒有一個複選框實際上覆制了數據。想想看,我所有的表單元素都有唯一的ID,所以也許有一個更簡單的方法? – Chris

+0

@Chris:嘗試引用(我的答案的第二部分)。顯然你需要第二個表單的前綴/後綴來保持ID的唯一性,但是你可以將選擇器改爲'$('#prefix'+ this.id).val($(this).val()) '。 – Matt

+0

嘿馬特..你更新它就像我發表我的評論,我編輯它,以反映你的編輯。乾杯隊友 – Chris

0

嘗試使用data屬性。使用

data-name="cartype[]"

並抓住它:$(this).data('name')

相關問題