2014-09-24 48 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