Search code examples
javascriptcopyaddeventlistenerbuttonclickgetelementsbytagname

How do I copy text from an <Input> by using getElementbyTagName?


I am trying to create a button that doesn't use ID to copy text from an input text field.

I thought the best way to do this would be using an event listener and then on click activate the function that would copy text from the input value.

HTML:

<div>
 <input type="text" value="copy this" readonly>
 <button type=button id='btn'>Copy URL</button>
</div>

JS:

  <script> 
  document.querySelect('#btn').addEventListener('click', function() {
   jimsFunction();
});
  
  function jimsFunction() {
  var copyText = document.getElementByTagName('input').value;
  copyText.select();
  copyText.setSelectionRange(0, 99999); 
  navigator.clipboard.writeText(copyText.value);
  alert("Copied: " + copyText.value);
  }    

</script>

Can someone point out what I'm doing wrong here?

Thanks


Solution

    1. First getting by tag is elements . You were missed s
    document.getElementByTagName ->document.getElemenstByTagName
    
    
    1. Loop elements and add event

    Try it :

    document.getElementById('btn').addEventListener('click', function() {
       jimsFunction(this)
    });
    let btns = document.getElementsByClassName('btn')
    Array.from(btns).forEach(ele => {
      ele.addEventListener('click', function() {
       jimsFunction(this)
      });
    })  
    function jimsFunction(input) {
      let ele = input.previousElementSibling
      ele.select()
      ele.setSelectionRange(0, 99999)
      navigator.clipboard.writeText(ele.value)
      alert("Copied: " + ele.value)
    }
    <div>
     <input type="text" value="copy this" readonly>
     <button type=button id='btn'>Copy URL</button>
    </div>
    <div>
     <input type="text" value="text 1" readonly>
     <button type=button class='btn'>Copy URL</button>
    </div>
    
    <div>
     <input type="text" value="text 2 (different)" readonly>
     <button type=button class='btn'>Copy URL</button>
    </div>

    You are duplicate id, you should change to class