Problem in javascript resolution [closed]

5

Should not the code below be executed automatically by getting the values of the id's and assigning them to the array ui?

var ui = ["input", "prompt", "heading"];
ui.forEach(function(id){
   ui[id] = document.getElementById(id);
});
    
asked by anonymous 03.01.2017 / 10:22

2 answers

3

With this code what I think you want is to store the elements that have these id's of the array ui, but it will have to be a slight modification since ui is not an object

var ui = ['input', 'prompt', 'heading'];
var eles = {} // objeto que vai armazenar os elementos com os id's de ui
ui.forEach(function(id) {
  eles[id] = document.getElementById(id);
});
console.log(eles);
<div id="input">Input</div>
<div id="prompt">Prompt</div>
<div id="heading">Heading</div>

Now we have all the elements saved in the variable eles .

This allows us to for example delegate an event to each of them:

var ui = ['input', 'prompt', 'heading'];
var eles = {} // objeto que vai aramazenar os elementos com os id's de ui
ui.forEach(function(id) {
  eles[id] = document.getElementById(id);
});
for(var ele in eles) {
 eles[ele].addEventListener('click', function() {
   alert('clicaste no elemento com o id: ' +this.id);
  });
}
<div id="input">Input (clica aqui)</div>
<div id="prompt">Prompt (clica aqui)</div>
<div id="heading">Heading (clica aqui)</div>

From this, you will have to write document.getELementById(..); for each of them, as well as write / delegate the events one by one for each element.

    
03.01.2017 / 10:38
2

When you have

ui[id] = document.getElementById(id);

What this does is to assign the ui properties with pointers to the DOM element. Not its value but the element itself.

If you want to have the values you should add .value like this:

ui[id] = document.getElementById(id).value;

Example:

var ui = {};
['a', 'b'].forEach(function(id) {
  ui[id] = document.getElementById(id).value;
});

console.log(ui);
<input id="a" value="letra A" />
<input id="b" value="letra B" />
    
03.01.2017 / 10:53