MrB
MrB

Reputation: 107

Optimising javascript onclick function that copies data from input field

I have a javascript function that copies information from a text input field to the clipboard, which functions just fine. However, I need this function to be able to handle multiple inputs or connect multiple onclick events to the same input field.

Basically, I'm looking for ways to optimise the following.

function h1Function() {
var copyText1 = document.getElementById("h1Input");
copyText1.select();
document.execCommand("copy");
alert("Copied the text: " + copyText1.value);
}
function h2Function() {
var copyText2 = document.getElementById("h2Input");
copyText2.select();
document.execCommand("copy");
alert("Copied the text: " + copyText2.value);
}

connected to the following html fields.

<h1><a href="#" onclick="h1Function()">abcdefg123456ABCDEFG - h1</a></h1>
<input type="text" value="<div class='h1 highlight'>Din tekst her</div>" 
id="h1Input" />
<h2><a href="#" onclick="h2Function()">abcdefg123456ABCDEFG - h2</a></h2>
<input type="text" value="<div class='h2 highlight'>Din tekst her</div>" 
id="h2Input" />

Any and all optimization tips will be appreciated

Upvotes: 0

Views: 162

Answers (1)

aaaaane
aaaaane

Reputation: 187

Just pass the id as a parameter to the function.

function h1Function(id) {
  var copyText1 = document.getElementById(id);
  copyText1.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText1.value);
}
<h1>
  <a href="#" onclick="h1Function('input1')">abcdefg123456ABCDEFG - h1</a>
</h1>
<input type="text" id="input1" value="<div class='h1 highlight'>Din tekst her</div>" 
id="h1Input" />
<h2>
  <a href="#" onclick="h1Function('input2')">abcdefg123456ABCDEFG - h2</a>
</h2>
<input type="text" id="input2" value="<div class='h2 highlight'>Din tekst her</div>" 
id="h2Input" />

Upvotes: 1

Related Questions