'Extract values from multiple elements and format them on the clipboard to paste into spreadsheet - JavaScript

I have a form with 21 elements of types 'input', 'select' and 'textArea', and I have an array of 21 element id's that correspond to these elements.

I'm trying to extract the 21 values of these elements and concatenate them into one long string, with a tab inserted between each value. The intention is to put this string on the clipboard and manually paste it into a row on a spreadsheet.

In the (non working) code below, at the line 'nextValue = ...' , the console says that nextElement is null, indicating that an element with that id doesn't exist. But it does exist. Could someone please point out what I'm doing wrong here? Thanks.

//this function is called by the onclick event of a button.
function clipToExcel() {
     let element_Ids = ['id1', 'id2', 'id3', 'id4', 'id5', 'id6', 'id7', 'id8',  
                        'id9', 'id10',  'id11', 'id12', 'id13',  'id14', 'id15', 
                        'id16', 'id17', 'id18', 'id19', 'id20', 'id21'];

     let nextElement, nextValue, valueString = "";
     for (let i = 0;  i < element_Ids.length;  i++) {   
       nextElement = document.getElementById(element_Ids[i]);   
       nextValue = nextElement.value;
// console.log(nextValue);              
       valueString += nextValue + "\t";
     }
     navigator.clipboard.writeText(valueString);

     alert('Data is now on the Clipboard in a format that can be Pasted into Excel');
}


Solution 1:[1]

You have everything in a <form> then it's easier than you think. Details are commented in example below. For more info on the form interface read on .elements property.

// Reference the form
const form = document.forms[0];
// Reference all fields of form
const io = form.elements;
// this is just to generate inputs for demo
for (let i = 0; i < 21; i++) {
  io[i].value = i;
}

/* 
Gather all form controls into a
HTMLCollection then convert it into an array
*/
const allFieldsNamedA = io.A;

// Iterate with .map()
const str = [...allFieldsNamedA].map(inp => inp.value + '\t');

// Then .join() the array into one string
console.log(str.join(''));
.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}
<form>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
  <input name='A'>
</form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1