Frank Frank - 3 years ago 119
HTML Question

Is there a way to copy content of a html button to another?

I am trying to copy the content of a button in a html page to another button, I tried the following code, it doesn't work, it can only copy text from one input field to another, how to do the same for buttons ?

<!DOCTYPE html>
<html>
<body>

Field1: <input type=text id=field1 value="Hello World!"><br>
Field2: <input type=text id=field2><br><br>
<button id=BT_1 type=button onclick=myFunction()>ABC</button><br>
<button id=BT_2 type=button onclick=myFunction()>123</button>

<P>
<button onclick="myFunction()">Copy Text</button>

<script>
function myFunction()
{
document.getElementById("BT_2").value = document.getElementById("BT_1").value;
document.getElementById("BT_2").value = document.getElementById("field1").value;
document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>

</body>
</html>


Prefer to have something like the following :

<button id=BT_1 type=button onclick=myFunction(BT_1)>ABC</button>

function myFunction(From_BT)
{
document.getElementById("BT_2").value = document.getElementById(From_BT).value;
}

Answer Source

Is this what you have in mind? https://jsfiddle.net/jimedelstein/asfh2q2c/4/

The value of the button is not the same as the innerHTML.

Another solution would be to leave your javascript as is, but use

<input type="button" value="Button Text" id="BT_1" onclick='myFunction()' ></input> 

See here for an example of both: http://permadi.com/tutorial/jsInnerHTMLDOM/

You can also create a function, let's call it copy_button_text that accepts two parameters the source button and target button, which we would call like so onclick='copy_button_text("BT_1", "BT_2")'. You will see in the fiddle, the myFunction() works, but each button actually uses this function to apply it's text to the other button.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download