Problem in solving javascript

Asked

Viewed 45 times

5

The code below should not be executed automatically by receiving id values and assigning them to the ui array?

var ui = ["input", "prompt", "heading"];
ui.forEach(function(id){
   ui[id] = document.getElementById(id);
});

2 answers

3


With this code what I think you want is to store the elements that have these id’s of the ui array, but it will have to be a slight modification because ui is not 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 stored in the variable eles.

This allows us for example to 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 minstrel you do not need to write document.getELementById(..); for each of them, as well as excuses to write/delegate the events one to one for each element.

  • Thank you very much Miguel! But the intention is not to index like this: array[Elementhtml] ?

  • You’re welcome @Lucastrino. Happy New Year, and welcome

  • @Lucastrino I think you are missing something, in this case it is an object in which each key is the name of the id, is not the element, associated to each key with respective value is that we have the elements

2

When you have

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

what it does is attribute to ui pointer properties for the DOM element. Not its value but the element itself.

If you want to have values you should join .value thus:

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" />

  • Yes, I expressed myself in a bad way. But it won’t index the ui array like this: ui[htm q element has one of the ui array ids]?

  • @Lucastrino if you want to have ui[elemento] you can’t use an object, you have to use a Map, that’s what you’re looking for?

  • No, that’s what I thought it was. But in reality, the above code does?

  • @Lucastrino The code in my answer holds the values of each input an array to, for example, send to the server and process that data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.