2011-05-05 97 views
2

我正在爲一位婚禮攝影師構建訂單,因此客人可以從他的網站的客戶端相冊部分訂購照片。jQuery添加表單輸入並更改輸入名稱

訪客在1到50張圖片之間訂購,所以我目前使用jQuery的clone()功能,這非常棒。

但是我還需要更改每個輸入的名稱attr,每次添加一個表單處理都可以在新輸入上獲取。

name="picture-1" 
add field 
name="picture-2" 

有誰知道這是可能的嗎?

我相信我可以每次使用addClass()clone()被調用,但是我怎樣才能讓addClass()數到?

謝謝

+1

如果服務器端語言是** PHP ** – diEcho 2011-05-05 11:45:02

+1

。 – diEcho 2011-05-05 11:50:55

+1

@diEcho:**如果**您正在服務器上使用PHP,請更好地使用'「來顯示您的jQuery代碼 – 2011-05-05 11:54:25

回答

5

你剛纔設置的克隆元素的name財產。 ( jQuery的1.6或以上使用prop; attr在1.5.2及以下貌似attr作品在兩個1.5和1.6; prop作品在1.6及以上)

但要注意的方式HTML表單工作,可以使用相同的名稱,它們都被髮送到服務器,您的代碼可以在其中處理所有這些數據(通常您使用的服務器端技術將它們設置爲數組或列表)。

例子:

HTML:使用

<form id='theForm'> 
    <input type='text' name='picture-1'> 
    <input type='button' id='btnMore' value='+'> 
</form> 

JavaScript的jQuery的:

$('#btnMore').click(function() { 
    var form, fields, newField; 

    form = $("#theForm"); 
    fields = form.find("input[name^='picture-']"); 
    newField = $(fields[0]).clone(); 
    newField.attr('name', 'picture-' + (fields.length + 1)); 
    newField.insertAfter(fields.last()); 
}); 

Live copy

+0

謝謝T.J. Crowder,我甚至沒有想過使用attr。 – eagleworks 2011-05-05 11:55:56

+0

@eagleworks:不用擔心,很高興幫助。 – 2011-05-05 11:56:46

1
$('input[name^="picture-"]',pointertoform).length 

...會給你真正PRES的數量輸入名稱以「picture-」開頭,您可以使用此編號創建新名稱。

但我更喜歡diEcho的評論的解決方案。

0

嘗試此(原始代碼)

$(some_cloned_element).each(function(i, elem){ 
    var newName = "yay_i_love_my_new_name"; 
    if ($.browser.msie === true){ // evil browser sniffing *cries* 
     $(elem).replaceWith(document.createElement(
      this.outerHTML.replace(/name=\w+/ig, 'name='+newName+'_'+i) 
     )); 
    } else { 
     $(elem).attr('name',newName+'_'+i); 
    } 
    $("body").append(some_cloned_element); 
}); 

檢查時I = 50然後休息/出口

更好的方法:使用名稱爲陣列狀name=picture[]

Refernece