2010-09-02 109 views
6

我有一個使用ajax動態創建的表單(因爲表單元素的數據必須來自數據庫),我想序列化表單的元素以提交阿賈克斯。我目前只是測試使用代碼從jQuery網站我的理論只是爲了看看,如果我可以拿起表單元素,這就是問題所在:jQuery serializeArray不拾取動態創建的表單元素

$(document).ready(function() { 
    $('#btnCustomSearch').live('click', function() { 
      $('#results').html(''); 
      alert($('#customSearchTable :input').serializeArray()); 
      // get all the inputs into an array. 
      var fields = $('#customSearchTable :input').serializeArray(); 
      jQuery.each(fields, function(i, field) { 
       $("#results").append(field.name + " = " + field.value + ", "); 
      }); 

      // now we'll reformat the data as we need 

      // here we'll send the data via ajax 

    }); 
}); 

我需要做一些改變的數據之前提交和這個代碼還沒有被寫入,但我發現,頁面上的任何輸入元素在頁面加載時都被拾取正確,任何使用Javascript填充的元素都被正確拾取,但是任何使用ajax創建的內容將被忽略。

我知道這通常使用「活」解決,但我不清楚如何解決這與serializeArray()。使用Ajax額外的表單元素被添加到#customSearchTable,這些是沒有被拿起。

任何幫助非常感謝。

感謝

+1

這個方法並不在乎什麼時候添加元素,看起來他們沒有被正確添加爲表單元素,你能發佈那些代碼嗎?例如,他們有他們的'name'屬性嗎? – 2010-09-02 11:45:42

+0

尼克,非常感謝,你是對的,動態生成的表單元素缺少名稱屬性.... DOH!非常感謝!! – Cydaps 2010-09-02 12:10:33

回答

7

我會在評論多一點這裏闡述:

當你調用.serializeArray()它通過循環只是作爲一個<form>屈服會或儘可能接近反正去提交的元素。關鍵部分is here

.filter(function() { 
    return this.name && !this.disabled && 
     (this.checked || rselectTextarea.test(this.nodeName) || 
     rinput.test(this.type)); 
}) 

正如<form>提交將不包括元素沒有name attribute,將.filter()呼叫使用this.name將篩選出來的人的那些元素被序列化。

+0

感謝Nick,希望澄清它對於有同樣問題的其他人。 – Cydaps 2010-09-03 07:41:50

+0

爲'