how do i copy to clipboard with the input or place

2019-03-05 11:58发布

问题:

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

回答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');
    }
}


回答2:

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;
});