Home > Enterprise >  Copy input on keyup to similar elements
Copy input on keyup to similar elements

Time:03-04

I'm looking for a way to copy input value on keyup to other identical input fields, so that they all contain the same value real-time. So basically I want to copy the current typed value to the other inputs. I can't make it work, though:

I have this html:

<input type="search"  placeholder="Search">
<input type="search"  placeholder="Search">
<input type="search"  placeholder="Search">

and this js:

getPhrase = () => {
  const phrase = document.querySelectorAll('.phrase');
  let input;

  for (let i = 0; i < phrase.length; i  ) {
    phrase[i].addEventListener('keyup', () => {
      input = phrase[i].value;
      console.log(input);
    });
  }
}

getPhrase();

I tried to add:

  for (let i = 0; i < phrase.length; i  ) {
    phrase[i].addEventListener('keyup', () => {
      input = phrase[i].value;
      console.log(input);
    });
    phrase.value = input // <-- This won't work.
  }

JsFiddle here. What am I missing?

CodePudding user response:

I am not sure if i understand it correctly, but if you want to copy the value to the other fields, then:

getPhrase = () => {
  const phrase = document.querySelectorAll('.phrase');
  let input;

  for (let i = 0; i < phrase.length; i  ) {
    phrase[i].addEventListener('keyup', () => {
      input = phrase[i].value;
      console.log(input);
      // loop thru the phrase's and give them value
      for (let j = 0; j < phrase.length; j  ) {
        phrase[j].value = input;      
      }
    });
  }
}

getPhrase();

This way you are able to modify any search value from any search fields.

CodePudding user response:

hi Kindly use the below code I think it will work for you

getPhrase = () => {
  const phrase = document.querySelectorAll('.phrase');
  let input;
  phrase[0].addEventListener('keyup', (e) => {
  for (let i = 0; i < phrase.length; i  ) {
      phrase[i].value = e.target.value
      console.log(input);
     } });
}

getPhrase();
  • Related