[英]jquery, append multiple values to one input hidden
I have a following variable 我有以下变量
var $pk3s_c = $('<input id = query_form_tbl_info_'+query_index +'_pk3ss[] name =query_form[tbl_info]['+query_index+'][pk3ss][] type = hidden></input>');
and an array 和一个数组
var pk3s = opts[tbl]["cols"];
during iteration through the array, I want to append the elements of an array to $pk3s_c
在遍历数组的过程中,我想将数组的元素附加到
$pk3s_c
$.each(pk3s, function(i,pk3){
$pk3s_c.attr('value',pk3);
})
the code above is not working, it shows me that I have appended only last element of a pk3s, and not all of them. 上面的代码不起作用,它向我显示我仅附加了pk3的最后一个元素,而不是全部。 How can I append each element of p3ks into my hidden input?
如何将p3ks的每个元素附加到隐藏的输入中?
For readability, I would pass the arguments as a parameter to the jQuery function 为了提高可读性,我会将参数作为参数传递给jQuery函数
Would look like 看起来像
var values = ['argument1', 'argument2', 'argument3']; var query_index = 43; var jqueryAttributes = { id: 'query_form_tbl_info_' + query_index + '_pk3ss[]', name: 'query_form[tbl_info][' + query_index + '][pk3ss][]', type: 'hidden', value: JSON.stringify(values) // if your server don't support HTML encoding, use the one below instead // value: "['"+values.join("','")+"']" }; var $newElement = $('<input/>', jqueryAttributes); alert('you element would look like : ' + $newElement[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
You aren't going to get an array into a string field without converting it into a string. 如果不将数组转换为字符串,就不会将其放入字符串字段。
The JSON format is very useful for this JSON格式对此非常有用
// convert the array to a string
var myString = JSON.stringify(myArray);
// put the string into the field as it's value
$('input').val(myString);
Javascript can interpret the resulting string and server side languages can easily convert it from a string into an array value they can understand (see for php , ruby ) Javascript可以解释生成的字符串,服务器端语言可以轻松地将其从字符串转换为他们可以理解的数组值(有关,请参见php , ruby )
Here is an example in a jsfiddle 这是一个jsfiddle中的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.