DEV Community

Cover image for Copy selected input to the clipboard in javascript.
ishrat
ishrat

Posted on

Copy selected input to the clipboard in javascript.

This code will first select the copy button and all checkbox elements. Then, it will add an event listener to the copy button. When the button clicks, the code will loop through all checkboxes, check if they are checked, and add their values to an array. Finally, it will combine the selected values into a single string and copy it to the clipboard.

<input type="checkbox" id="checkbox1" value="value1"> Option 1
<input type="checkbox" id="checkbox2" value="value2"> Option 2
<input type="checkbox" id="checkbox3" value="value3"> Option 3
<br>
<button id="copy-button">Copy Selected</button>

Enter fullscreen mode Exit fullscreen mode
const copyButton = document.getElementById('copy-button');
const checkboxes = document.querySelectorAll('input[type="checkbox"]');

copyButton.addEventListener('click', () => {
  const selectedValues = [];

  // Loop through all checkboxes
  for (const checkbox of checkboxes) {
    // Check if the checkbox is checked
    if (checkbox.checked) {
      // Add the checkbox value to the array
      selectedValues.push(checkbox.value);
    }
  }

  // Check if any values are selected
  if (selectedValues.length > 0) {
    // Combine the selected values into a single string with newline separators
    const copyText = selectedValues.join('\n');

    // Copy the text to the clipboard using ClipboardJS (optional)
    // You can install and use the ClipboardJS library for better compatibility
    // https://clipboardjs.com/
    // const clipboard = new ClipboardJS('#copy-button');
    // clipboard.copy(copyText);

    navigator.clipboard.writeText(copyText).then(() => {
      console.log('Values copied to clipboard!');
    }, (error) => {
      console.error('Error copying values:', error);
    });
  } else {
    alert('Please select at least one option to copy.');
  }
});
Enter fullscreen mode Exit fullscreen mode

Additional notes:

You can modify the code to include custom separators between the values.
You can use the ClipboardJS library for better compatibility and additional features.
You can add error handling to handle situations where copying to the clipboard fails.
You can adjust the styling and functionality based on your specific needs.

Top comments (0)