Stuart Washbourn Stuart Washbourn - 3 months ago 18
HTML Question

javascript copy and paste

I currently have a table that loops through my database and displays all the results I request, then i'm using jquery to select a row on click and copy both fields that i've selected and paste the code and description into two seperate input boxes

<table id="table "class="border_bottom">
<?php while ($row = mysql_fetch_array($query)) { ?>
<tr id="table" class="border_bottom">
<td width="100px" class="copy" align="center"><?php echo $row['code']; ?></td>
<td width="500px" align="center"><?php echo $row['description']; ?></td>
</tr>
<?php } ?>
</table>


<input type="text" class="paste" value="" style="width:125px;height:18px;text-align:center;" readonly />

<input type="text" placeholder="Description" readonly></input>


<script type="text/javascript">
$(document).on('click', '.copy', function(e){
e.preventDefault(); //for <a>
$('.paste').val($(this).text());
});
</script>


the java code works perfectly when i select a code, it will copy and paste but ive tried to figure out how to make it copy both and paste but with no luck, any help would be appreciated

Answer

To get both code and description into your input:

Generate your tr with the same class name "row":

Note: remove the id from the tr because id should be unique

<table id="table" "class="border_bottom">
    <?php while ($row = mysql_fetch_array($query)) { ?>
        <tr class="row border_bottom">
            <td width="100px" align="center"><?php echo $row['code']; ?></td>
            <td width="500px" align="center"><?php echo $row['description']; ?></td>
        </tr>
    <?php } ?>
</table>

Add id to your input field to be reference more easily:

<input type="text" id="code" class="paste" value="" style="width:125px;height:18px;text-align:center;" readonly />
<input type="text" id="desc" placeholder="Description" readonly />

Update your jquery, when you click the row, get the code into your code input field, get your description to your description input field

$(document).on('click', '.row', function(e){
    e.preventDefault(); //for <a>
    $('#code').val($(this.children[0]).text());
    $('#desc').val($(this.children[1]).text());
});

You may reference the following jsfiddle for working example: https://jsfiddle.net/hntmvnmq/