How to make a "Copy to Clipboard" button using javascript

1
0
-1

I have a form with a input widget that will generate value based on value of other input field.

I need to to make a button to let user copy the value to clipboard to let user save it.

I found a simple JavaScript code beow that let me copy a value of a field:

function CopyToClipboard() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
}

How can I find the id of the widget to be able to use he above code?

Or is there any way else that I can use?

Comments

Submitted by Dibyajit.Roy on Sun, 03/14/2021 - 08:40

Hello
All widgets can be edited in new version of BonitaSoft.
The Input widget is called as pbInput

Submitted by ndhv1983_2529106 on Mon, 03/15/2021 - 02:46

If I have a lot of input widget on the page, will they all have id = " pbInput"?

If so, how can a let the JavaScript know exactly which input it should select?

1 answer

1
0
-1

After search around for a while, I have found the solution:

If I have a lot of input widget on the page, they all do not have id property, but name that is unique.

However, I have no way to decide which name the input field will have, so I have to run the page and inspect the generated HTML source to get the name, then hardcode in the JavaScript code.

The step I did is as below:

1. Add a JavaScript expression variable in UI Designer:

return function() {
    /* Get the text field */
    var copyText = document.getElementsByName("pbInput1");
    /* Select the text field */
    copyText[0].select();
    /* Copy the text inside the text field */
    document.execCommand("copy");
}

2. Duplicate default button widget and create a new one by following the link Create custom button to run JavaScript function

For people who don't know how, after create the custom button widget:

  • Add a properties, in my case, I set the name "javascriptVariable", "Treat value as" = "Bidirectional bond"
  • In controller, use below code instead of the default.
this.action = function action() {
    $scope.properties.javascriptVariable(); 
  };

3. In the form, add custom button. In its properties panel, scroll to the last to see the new property we add in step 2, and set the value to the name of the variable in step 1.

Comments

Submitted by Dibyajit.Roy on Mon, 03/15/2021 - 06:32

Thank you for the Sharing the steps and the code. I am sure this will be helpful to many people.

Notifications