I have an array created by taking the values of all the links in a div, when I add the values to a textarea to send them to my server, it's o开发者_JS百科nly pulling the last one, using console I noticed that the array is holding all the values, as is the alert when I set it, so how can I concatenate all the values into one long string with commas or something? Here's my code
$(".populate").click(function(){
var array = $.makeArray( $('li.item-link a'));
jQuery.each(array, function(index, value) {
console.log("index", index, "value", value);
alert(value);
$("#CAT_Custom_196863").val(value);
});
});
Anyone any ideas?
All the Best Tara
Your $("#CAT_Custom_196863").val(value);
line is setting the entire value to the latest value
.
Instead use something like:
$("#CAT_Custom_196863").val($("#CAT_Custom_196863").val() + ', ' + value);
You can use the join method of Javascript arrays:
$("#CAT_Custom_196863").val($.MakeArray($('li.item-link a')).join(", "));
BTW Blair McMillan is correct, you're setting the entire value, not adding to it.
The val method replaces the current value. Try this instead:
$(".populate").click(function(){
var array = $.makeArray( $('li.item-link a'));
var newVal = '';
jQuery.each(array, function(index, value) {
console.log("index", index, "value", value);
alert(value);
newVal += value + ','; // comma?
});
// In order to skip the last comma, uncomment this line:
// if(newVal.length > 0) newVal = newVal.substr(0, newVal.length - 1);
$("#CAT_Custom_196863").val(newVal);
});
try
$.map(arr, function(value, index) {
return arr.join(",");
});
rest is logic
精彩评论