I am looping through the value of a select tag but I want to concatenate the data as follows
codcli: ("5590541-2", "134054-9")
This is my code:
codcli='';
var val=document.getElementById('show_product');
for (i=0;i< val.length;i++) {
if(val[i].selected){
codcli += '(' + '"' + val[i].value + '",' + ')';
}
}
codcli=codcli.slice(0,codcli.length -1);
When executing it, the data remains as follows, which is not what I want:
codcli: ("5590541-2",)("134054-9",
The code does not work due to a concatenation problem, as the colleagues have already pointed out.
The way I see it, it's much simpler to store the values in an array and then output each element of the array separated by commas using
join
.For example:
Let's see a real test:
This
it's because according to the question you want the values in quotes. If you just wanted the values it would be simpler:
And the output would be:
For example:
You can just run a
map
on the collection ofoptions
to get just the values. Then usingjoin
you can concatenate each value in the collection using a delimiter.Example
The parentheses should go outside the for, not inside. Leaving it inside the loop only causes it to repeat forever. You add the parentheses before and after the for and you would have left:
You need to concatenate the parentheses outside the loop like this: