1

I want to create an element with javascript which should look like below:

<span onClick="return fieldtoclipboard.copyfield(event, '.uniqueId()')">Select All</span>

I want to replace .uniqueId() with a unique ID generated. How can I achieve this?

D M
  • 5,769
  • 4
  • 12
  • 27
nuet
  • 219
  • 4
  • 12

2 Answers2

1

Here is what you need:

var spanElement = document.createElement('span');
spanElement.innerHTML = 'Select All';
spanElement.uniqueId = 'your_unique_id'
spanElement.onclick = function() {
  console.log(this.uniqueId);
};

document.body.appendChild(spanElement);

You can also play with it here:

http://fiddle.jshell.net/jrybt60n/

axaq
  • 84
  • 3
1

Rather creating the span element dynamically, use a intermediate function:

function copyfieldWithUniqueID(event) {
    var uniqueID = uniqueID() // get a unique ID
    return fieldtoclipboard.copyfield(event, uniqueID);
}

HTML:

<span onclick="copyfieldWithUniqueID(event)">Select All</span>

(Use onclick instead of onClick attribute)

And from the answer Create GUID / UUID in JavaScript?

Define a function:

function uniqueID() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
    }
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
}
Community
  • 1
  • 1
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121