nuet
nuet

Reputation: 219

how to add a unique id to a onclick event

I am having some code between pre tags and I want to catch al that code with an onclick event My html structure is like below:

<div class="Message">
  <div class="surroundpre">
     <span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span>
     <pre class="CodeBlock id="id22015640">
        <!-- code goes her -->
     </pre>
  </div>
 </div>

The pre elements and the div with class surroundpre is created by javascript. The unique id for the pre:

$('pre').each(function(){

    if ($(this).attr('id') == undefined){
        $(this).attr('id','id'+Math.floor((Math.random() * 99999999) + 1))
    }
 });

The div with surroundpre is created like below:

$('.Message .CodeBlock', this).wrap('<div class=surroundpre></div>');

The span is created with php variable:

 $SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span><br />';

in combination with:

$('.surroundpre').prepend('$SelectButton');

My question: the id1 in the php variable should be replaced with the same unique id as in the pre tag. How can I achieve this? Or is there an other method to achieve this?

Upvotes: 1

Views: 2130

Answers (1)

Chris O&#39;Kelly
Chris O&#39;Kelly

Reputation: 1893

This might work for you, make a few changes, first in PHP:

$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, this.getAttribute(\"data-block-id\"))">[Select and Copy]</span><br />';

Then in JS:

$('pre').each(function(){
    var id;
    if ($(this).attr('id') == undefined){
        id = 'id'+Math.floor((Math.random() * 99999999) + 1);
        $(this).attr('id',id);
        $(this).prev('span').attr('data-block-id',id);
    }
 });

Now the id generated in js is attached to the span at the same time of creation, when it is available to you, and the pregenerated (in PHP) onclick event can access it when it needs it (as long as that is after the ID setting code has run).

Upvotes: 1

Related Questions