Home > Net >  convert repetitive variables and functions into loops
convert repetitive variables and functions into loops

Time:11-07

can anyone help me how to convert this into loops :) hi newbie here in javaScript:) the output of this is a input form, i want all the value that typed into the form to be appear instantly by using keyup event thanks in advance :)

let textarea = document.querySelectorAll('span')
let bns = document.querySelector('#bns');
let id = document.querySelector('#id');
let img = document.querySelector('#img');
let lg = document.querySelector('#lg');

textarea.forEach(function (item, index) {
    item.classList.add('t'  `${index}`)
    //console.log(item)
})

let input = addEventListener('keyup', function(){
    let strbns = bns.value;
    let strid = id.value;
    let strimg = img.value;
    let strblg = lg.value;
    document.querySelector('.t0').innerText = strbns
    document.querySelector('.t1').innerText = strid
    document.querySelector('.t2').innerText = strimg
    document.querySelector('.t3').innerText = strblg
});

output enter image description here

i create variables to each input field and used the keyup event to print the out put to individual span. yes it works but its so repetitive and i thinks it is much better if it's convert it into for loops but i dont know how

CodePudding user response:

Use two arrays which are the same length. Then you can loop over one of them with the index to get the corresponding element:

const elements = [bns, id, img, lg];
const selectors = [".t0", ".t1", ".t2", ".t3"].map((s) => document.querySelector(s));

addEventListener('keyup', function() {
    elements.forEach((el, index) => {
        selectors[index].innerText = el.value;
    });
});

CodePudding user response:

You can make it more optimal by give a try like this.

const formData = {
  bns: document.querySelector('#bns'),
  id: document.querySelector('#id'),
  img: document.querySelector('#img'),
  lg: document.querySelector('#lg')
};

document.addEventListener('keyup', function() {
    Object.keys(formData).forEach((key, index) => {
    document.querySelector(`.t${index}`).innerText = formData[key].value
  })
});
<input type="text" id="bns"/>
<input type="text" id="id"/>
<input type="text" id="img"/>
<input type="text" id="lg"/>

<div ></div>
<div ></div>
<div ></div>
<div ></div>

  • Related