nuet
nuet

Reputation: 219

how to create Element with onclick and unique id with javascript

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?

Upvotes: 1

Views: 300

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

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

Upvotes: 1

axaq
axaq

Reputation: 84

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/

Upvotes: 1

Related Questions