Concatenate data in javascript

Question:

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 is as follows, which is not what I want:

codcli: ("5590541-2",)("134054-9",

Answer:

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 save the values ​​to an array and then get each element of the array separated by commas using join .

For example:

items=[];
var val=document.getElementById('show_product');
for (i=0;i< val.length;i++) { 
    if(val[i].selected){
        items.push(val[i].value); 
    }
}         
var codcli=`("${items.join('","')}")`;
console.log(codcli);

Let's see a real test:

 var items=[]; /*Esto es lo que ocurriría en el for*/ items.push("5590541-2"); items.push("134054-9"); /*Variable final*/ var codcli=`("${items.join('","')}")`; /*Prueba*/ console.log(codcli);

This

var codcli=`("${items.join('","')}")`

It is because according to the question you want the values ​​in quotes. If you just wanted the values ​​it would be simpler:

var codcli=`(${items.join()})`;

And the output would be:

(5590541-2,134054-9)

For example:

 var items = []; /*Esto es lo que ocurriría en el for*/ items.push("5590541-2"); items.push("134054-9"); /*Variable final*/ var codcli = `(${items.join()})`; /*Prueba*/ console.log(codcli);
Scroll to Top