2014-09-24 46 views
0

我在玉這樣一個隱藏的輸入字段:添加到HTML輸入數組

input(name='saintForm[quotes][]', type='hidden') 

我想使用jQuery從動態無序列表添加到該數組,但不知道如何。這是我的失敗嘗試:

$('#form').on('submit', function(e){ 
    e.preventDefault(); 
    $('.quote').each(function (i){ 
     var item = $(this).text().replace(' (x)',''); 
     $("input[name='saintForm[quotes][]']").push(item); 
    }); 
    this.submit(); 
    }); 
+1

你沒有數組,你有一個數組式的jQuery對象,它沒有'push'方法。你可能在尋找jQuery的'add()'方法,但不知道'item'是什麼,這是不可能知道的? – adeneo 2014-09-24 18:54:29

+0

對不起,添加了該項目。我嘗試使用add(),但服務器上的結果仍顯示空白 - 引號:[''] – 2014-09-24 18:57:52

+0

正如@adeneo提到的,您沒有數組。我認爲唯一的方法就是遍歷引號並逐個添加到輸入值。 – 2014-09-24 19:04:23

回答

0

如果您只是向默認表單功能添加值,則可以使用值創建輸入。

// grab your form and wrap it in jQuery 
var myForm = $('#form'); 

// list teo the submit event 
myForm.on('submit', function(e) { 
    e.preventDefault(); 

    $('li.quote').each(function() { 
     $('<input />', { 
      type: 'text', // input type 
      name: 'saintForm[quotes][]', // the name of the form input 
      value: $(this).text() // the text from the current list-item 
     }).appendTo(myForm); // append each input to the form  

    }); 

    myForm.submit(); // submit the form 

}); 

當然你也可以發送各種任意數據到服務器,可輕鬆使用AJAX,但如果你只是用普通的形式提交我想這是做一個好辦法。

+0

這適用於一些小修改。首先,我能夠擺脫隱藏的元素,因爲它們是動態創建的,其次我將類型從「文本」更改爲「隱藏」。謝謝。 – 2014-09-24 19:52:08