0

I can make variables one by one like this:

var bookName = document.getElementById('bookName').value,
    author = document.getElementById('author').value,
    translator = document.getElementById('translator').value,
    pageCount = document.getElementById('pageCount').value,
    publisher = document.getElementById('publisher').value,
    isbn = document.getElementById('isbn').value,
    printingYear = document.getElementById('printingYear').value;

But it's so hard to write and it doesn't fit with the DRY rule. So I changed the code to this:

function variableMaker(argument) {
  var tags = document.getElementsByTagName(argument);
  for (var i = 0; i < tags.length; i++) {
    var tags[i].name = tags[i].value;
  }
}

variableMaker(input);

But I can't understand if it is the true way or if it is working? How do I check if it's true or not?

In this code, I tried to get the computer find all the input tags and make variables with their name property and assign it to its values for each of them.

SGhaleb
  • 979
  • 1
  • 12
  • 30
  • Possible duplicate of [How do I create dynamic variable names inside a loop?](https://stackoverflow.com/questions/8260156/how-do-i-create-dynamic-variable-names-inside-a-loop) – Koby Douek Aug 09 '17 at 11:01

1 Answers1

1

If I understand correctly then you want to gather data from all <input> elements. If so, then you need to call it like this:

variableMaker('input');   // use quotes!

Still even then your function does not return anything, it just ends.

You'd also better create your own object for the return collection, instead of adding values to an existing object.

Here is a working solution:

function variableMaker(tagName) {
  var elements = document.getElementsByTagName(tagName);
  var items = {};
  for (var i = 0; i < elements.length; i++) {
    var elem = elements[i];
    items[elem.id] = elem.value; // Use id as key, each points to the corresponding value.
  }
  return items;
}

var values = variableMaker('input');

console.log(values);        // show the entire return object

console.log(values.author); // access individual items from the return object
console.log(values.isbn);
<input type="text" id="author" value="Dahl">
<input type="text" id="isbn" value="1234">

.

Peter B
  • 22,460
  • 5
  • 32
  • 69