I currently have a onclick even on a div as follow
function copyToClipboard(e) {
var textBox = document.getElementById(e.id);
console.log(textBox);
textBox.select();
document.execCommand("copy");
}
<div class="form-inline m-2">
<input type="text" class="form-inline" name="myvalue" id="{{ p.id }}" value="https://diccionarioespañol.com/significado/{{ p.nombre|lower }}/" readonly />
<button onclick="copyToClipboard(this)">📋</button>
</div>
The issue is I'm unable to get the textBox to show the input data. Instead it shows null. So how do I get the id from the div or the url value sent to the clipboard
Your button is not referencing the input. Try this.
function copyToClipboard(theId) {
var textBox = document.getElementById(theId);
console.log(textBox);
textBox.select();
document.execCommand("copy");
}
<div class="form-inline m-2">
<input type="text" class="form-inline" name="myvalue" id="{{ p.id }}" value="https://diccionarioespañol.com/significado/{{ p.nombre|lower }}/" readonly />
<button onclick="copyToClipboard('{{ p.id }}')">📋</button>
</div>
If you are depending on the click event, you can check the parent from which you can find the input node.
Working Fiddle
function copyToClipboard(e) {
const input = Array.from(e.target.parentNode.children).find(node => node.nodeName === "INPUT");
console.log(input.id);
var textBox = document.getElementById(input.id);
console.log(textBox);
textBox.select();
document.execCommand("copy");
}
<div class="form-inline m-2">
<input type="text" class="form-inline" name="myvalue" id="p.id"
value="https://diccionarioespañol.com/significado/{{ p.nombre|lower }}/" readonly />
<button onclick="copyToClipboard(event)">📋</button>
</div>
You can use closest to get the parent then use the parent to query the input and then get the event targets id. I however did not use the onclick attribute. I added a selector to the button and used addEventListsner() with that selector instead passing the function as a callback into the listener.
function copyToClipboard(e) {
const target = e.target.closest('.form-inline').querySelector('input');
var textBox = document.getElementById(target.id);
console.log(target);
textBox.select();
document.execCommand("copy");
}
document.getElementById('button').addEventListener('click', copyToClipboard)
<div class="form-inline m-2">
<input type="text" class="form-inline" name="myvalue" id="{{ p.id }}" value="https://diccionarioespañol.com/significado/{{ p.nombre|lower }}/" readonly />
<button id="button">📋</button>
</div>