1

I have a simple form: https://jsfiddle.net/skootsa/8j0ycvsp/6/

<div class='field'>
<input placeholder='Nickname' type='text'>
</div>
<div class='field'>
<input placeholder='Age' type='text'>
</div>

How would I get a button that copied the contents of each input box + the "placeholder" attribute (or class name)? So that the clipboard results looked like this:

Nickname: Johnnyboy

Age: 22

amy-gr8njr
  • 13
  • 3
  • Probably duplicate of [this](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Xatyrian Jun 15 '17 at 13:12

2 Answers2

1

You need to:

  1. create an invisible element to copy the data
  2. get the data from your form and set it to the previous element
  3. select it
  4. call document.execCommand('copy') to copy the selected text to the clipboard

I have updated your fiddle, check it out https://jsfiddle.net/8j0ycvsp/9/

In case you want the code

function copyToClipboard() {

    /*get inputs from form */
    var inputs = document.querySelectorAll("#the-form input[type=text]");

    /*do a copy of placeholder and contents*/
    var clipboardText = ''
    for (var i = 0, input; input = inputs[i++];) {
        clipboardText += input.placeholder+': '+(input.value ? input.value : '' )+'\n';     
    }

    /*create hidden textarea with the content and select it*/
    var clipboard = document.createElement("textarea");
    clipboard.style.height = 0;
    clipboard.style.width  = 0;
    clipboard.value = clipboardText;
    document.body.appendChild(clipboard);
    clipboard.select();

    console.log(clipboard.value);

    /*do a copy fren*/
    try {
        if(document.execCommand('copy'))
            console.log('Much succes, wow!');
        else 
            console.log('Very fail, wow!');

    } catch (err) {        
        console.log('Heckin concern, unable to copy');
    }
}
Prete
  • 97
  • 1
  • 5
0

So give it a try

var input = document.querySelectorAll('.field input');

document.getElementById('submit').addEventListener('click', function () {
 var innerHTMLText = "";
 for (var i = 0; i < input.length; i++) {
  innerHTMLText += input[i].placeholder + ':' + input[i].value + '      ';
 }
 console.log(innerHTMLText);
 document.getElementsByClassName('bix')[0].innerHTML = innerHTMLText;
});
yang
  • 1
  • 4