How can I do a STRING when iterating the values of an ARRAY?

0

From a screen I get the ID and the VALOR of a group of INPUT TEXT with the following code:

   var docs = document.getElementsByName('ftp_desc');

    for (var i = 0; i < docs.length; i++){

        console.log('id: ' + docs[i].id + ',' + 'value: ' + docs[i].value);
    }

 <input id="1" name="ftp_desc"  maxlength="256" placeholder="Añade una descripción" required="required" type="text">
 <input id="2" name="ftp_desc"  maxlength="256" placeholder="Añade una descripción" required="required" type="text">
 <input id="3" name="ftp_desc"  maxlength="256" placeholder="Añade una descripción" required="required" type="text">

How can I do a STRING of the ID arrangement and one of the VALUE?

Example:

var ids = "1,2,3";
var values = "Desc1,Desc2,Desc3"
    
asked by Ricardo Sauceda 06.11.2017 в 19:17
source

2 answers

1

You can use the methods Object.keys () and Object.values () to obtain the values and keys of a array (obj) that you create and fill within the for , in addition to the join () to format it with a (,)

tab

var btn = document.getElementById('action');
btn.addEventListener('click',function(){
	var docs = document.getElementsByName('ftp_desc');
	var obj = {};//creamos el array
    for (var i = 0; i < docs.length; i++){
        obj[docs[i].id] = docs[i].value; // almacenamos los valores y clave id
    }
    console.log(Object.keys(obj).join(","));
    console.log(Object.values(obj).join(","));
});
<input id="1" name="ftp_desc"  maxlength="256" placeholder="Añade una descripción" required="required" type="text">
<input id="2" name="ftp_desc"  maxlength="256" placeholder="Añade una descripción" required="required" type="text">
<input id="3" name="ftp_desc"  maxlength="256" placeholder="Añade una descripción" required="required" type="text">
<button id="action">Aceptar</button>
    
answered by 06.11.2017 / 19:28
source
1

You can solve it by adding the ids and the values that you find in their respective variables, to end up having them all.

var docs = document.getElementsByName('ftp_desc');
var ids = '';
var values = '';

for (var i = 0; i < docs.length; i++){
    //Si es el último elemento no añado la coma, sino si la añado
    separator = (i == docs.length - 1) ? "" : ", ";
    //Agrego el nuevo id a la variable ids
    ids += docs[i].id+separator;
    //Agrego el nuevo valor a la variable values
    values += docs[i].value+separator;
    console.log('id: ' + docs[i].id + ',' + 'value: ' + docs[i].value);
}

//Aquí podras ver sus valores
console.log(ids);
console.log(values);
    
answered by 06.11.2017 в 19:28