Home > Software engineering >  Why copy button desn't targetting to match textarea when i click it?
Why copy button desn't targetting to match textarea when i click it?

Time:01-10

Copy target is doesn't matching in true table data

I try to make a copy (salin) button to copying every data on text area in table data / table. But the problem is the target not match to the textarea which it's should be targetting to copy. Please help me. I use Codeigniter and Javascript. Here the code:

TABLE:
<tbody>
                        <?php
                        foreach ($orderresep as $row) :
                        ?>
                            <tr>
                                <td><?= $row->NOREG; ?></td>
                                <td><?= $row->NORM; ?></td>
                                <td><?= $row->DESKRIPSI; ?></td>
                                <td><?= $row->PEMBERI_RESEP; ?></td>
                                <td><?= $row->NAMA; ?></td>
                                <td>
                                    <textarea  id="text-copy" readonly value="">
                                      <?= $row->GROUPP; ?>
                                    </textarea>
                                    <button  onclick="copyText()">
                                        <i ></i> Salin
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>

JAVASCRIPT:
<script type="text/javascript" lang="javascript">
    function copyText() {  
    document.getElementById("text-copy").select();   
    document.execCommand("copy");
}
</script>

CodePudding user response:

The problem is that all the textareas have the same id. document.getElementById will look up the first element that matches the id and return it, this is why you always get the first row on the table.

You could try this:

    <button onclick="copyText(event)">Salin</button>

    function copyText(event) {
      const textArea = event.target.previousElementSibling;
      textArea.select();   
      document.execCommand("copy");
    }

What this code does is pass the current event into the copyText function then traverses the DOM to the next element above it which is your textarea.

The other option would be to add an index to your for loop and add it to the id of the element, then use that to look up the correct row.

  • Related