简体   繁体   中英

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

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM