how do i copy to clipboard with the input or placeholder name?

。_饼干妹妹 提交于 2019-12-02 11:14:09

问题


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


来源:https://stackoverflow.com/questions/44568404/how-do-i-copy-to-clipboard-with-the-input-or-placeholder-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!