user3180931 user3180931 - 7 months ago 9
Javascript Question

Click on an element: copy its text to an input field

I searching a method to copy text to an input field, text can be in some tag or - it doesn't matter, but after clicking on this value I need to put this to input field (type text). I think it is possible with JavaScript/jQuery, but I don't know how to write script like this.

Answer

Just look at this example

HTML PART

<div class="copy">Copy me</div>
<span class="copy">Hey copy me</span>
<a href="#" class="copy">Me too</a>

<input type="text" class="paste" value="" />

JQuery PART

$(document).on('click', '.copy', function(e){
   e.preventDefault(); 
   $('.paste').val($(this).text());
});

SEE IN ACTION