Problem copying to clipboard with clipboard.js [duplicated]

0

I'm trying to copy the contents of a cell in a table using a button with JavaScript and the library clipboard.js

Each cell has a different value and that value arrives with PHP at foreach and is displayed with $item->resultado . The problem is that this variable is a String that contains a json in a format similar to this:

[{"_id":"5a5c9ed7f59787032fff7bba","index":0,"guid":"8171d24e-e8ed-43d6-a115-229390f8a8d2","isActive":false,"balance":"$2,158.78","picture":"http://placehold.it/32x32","age":31,"eyeColor":"blue","name":"Dianna Gonzales","gender":"female","company":"DATACATOR","email":"[email protected]","phone":"+1 (958) 555-2659","address":"614 Conduit Boulevard, Catharine ... }]

I think my problem comes with the quotes, since it only remains copied to where it is with the first, that is, copy: [{

How can I solve this problem? I leave my code:

<script type="text/javascript">
var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
    console.info('Accion:', e.action);
    console.info('Texto:', e.text);
    console.info('Trigger:', e.trigger);
    alert();
    alert();
    alert();
    e.clearSelection();
});

clipboard.on('error', function(e) {
    console.error('Accion:', e.action);
    console.error('Trigger:', e.trigger);
});
</script>
    <?php $resultado = [{"_id":"5a5c9ed7f59787032fff7bba","index":0,"guid":"8171d24e-e8ed-43d6"}];
    ?>
    <button class="btn" data-clipboard-text="<?php $resultado; ?>">Copiar texto</button>
    
asked by Norak 16.01.2018 в 10:14
source

1 answer

1

Sure. Note that the value of the data-clipboard-text attribute is enclosed in double quotes. As soon as he finds another double quote, he interprets that the attribute value ends there.

You should "escape" the double quotes in the value as &quot; .

See what result you would give as you have it (first button) and escaping the quotes (second button):

$(function(){
  console.log('Primer botón: ', $('.btn').data('clipboard-text'));
  console.log('Segundo botón: ', $('.btn2').data('clipboard-text'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button class="btn" data-clipboard-text="[{"_id":"5a5c9ed7f59787032fff7bba","index":0,"guid":"8171d24e-e8ed-43d6"}]">Copiar texto</button>

<button class="btn2" data-clipboard-text="[{&quot;_id&quot;:&quot;5a5c9ed7f59787032fff7bba&quot;,&quot;index&quot;:0,&quot;guid&quot;:&quot;8171d24e-e8ed-43d6&quot;}]">Copiar texto</button>
    
answered by 16.01.2018 / 11:13
source