Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  26] [ 1]  / answers: 1 / hits: 171191  / 9 Years ago, sun, november 22, 2015, 12:00:00

I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.



function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
return checkbx;
}


And to call it I use:



<button id=btn_test type=button >Check</button>
<script>
document.getElementById('btn_test').onclick = function() {
var checkedBoxes = getSelectedCheckboxes(my_id);
alert(checkedBoxes);
}
</script>


Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:



checkbx = document.execCommand(copy);


or



checkbx.execCommand(copy);


at the end of the function and then calling it like:



<button id=btn_test type=button onclick=getSelectedCheckboxes('my_id')>Check</button>


But it does not work. No data is copied to clipboard.


More From » copy

 Answers
41

OK, I found some time and followed the suggestion by Teemu and I was able to get exactly what I wanted.



So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx, and then copies their unique name to the clipboard.



JavaScript function:



function getSelectedCheckboxes(chkboxName) {
var checkbx = [];
var chkboxes = document.getElementsByName(chkboxName);
var nr_chkboxes = chkboxes.length;
for(var i=0; i<nr_chkboxes; i++) {
if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
}
checkbx.toString();

// Create a dummy input to copy the string array inside it
var dummy = document.createElement(input);

// Add it to the document
document.body.appendChild(dummy);

// Set its ID
dummy.setAttribute(id, dummy_id);

// Output the array into it
document.getElementById(dummy_id).value=checkbx;

// Select it
dummy.select();

// Copy its contents
document.execCommand(copy);

// Remove it as its not needed anymore
document.body.removeChild(dummy);
}


And its HTML call:



<button id=btn_test type=button onclick=getSelectedCheckboxes('ID_of_chkbxs_selected')>Copy</button>

[#64308] Thursday, November 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chazw

Total Points: 127
Total Questions: 129
Total Answers: 92

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
;