Anuska
Anuska

Reputation: 91

Copy value from input field

I need to copy the value from the input field to the clipboard. Instead of getting the value of the input field I get null.

Here is my Code:

<input type="text" value=${model.anchor_url} id=${properties.anchor_name}>
<button class="c-button" onclick="myFunction()">
    <span class="c-button__label">Copy</span>
</button>
<div data-sly-test="${model.anchor_url}">
    <p>URL from Model :</p>
    <pre>${model.anchor_url}</pre>
</div>
function myFunction() {
    const field = document.getElementById(`${properties.anchor_name}`);
    navigator.clipboard.writeText(field);
    alert("Copied the text to clipboard: " + field);
}

The value for field variable results null even though the id exist and it has a value.

Upvotes: 0

Views: 1969

Answers (3)

Anuska
Anuska

Reputation: 91

Thanks for all the help. It appears due to cross site scripting prevention JS can not be executed from html for the site I develop but has to be built using TypeScript.

Upvotes: 0

Aditya
Aditya

Reputation: 1329

You are trying to copy the element, instead of it's Value, you have to get it's Value using element.value, also if the value of field variable is null, this means the Element you are trying to get doesn't exist with that Element ID

And also, you were trying to copy the whole element instead of it's value, So Replace the first line in your function with this one:

const field = document.getElementById(properties.anchor_name).value;

Also there is no need to put template literals in your code as you can do so without that too!

For example assume there is a variable element_ID which can be written in JS like this:

var element_ID = "myInput"

now i want to get that Element, so I can just directly do this:

document.getElementById(element_ID)

instead of this:

document.getElementById(`${element_ID}`)

Upvotes: 0

Maik Lowrey
Maik Lowrey

Reputation: 17556

You get an Object with this line: document.getElementById(${properties.anchor_name}). With the parameter value you will get the value from the input field.

So you have to try:

const field = document.getElementById(`${properties.anchor_name}`).value;

Upvotes: 1

Related Questions