Sunday, March 11, 2012

Copy or duplicate column data in a table using context menu

This is a simple post used to copy data in a cell of a table to other cells of the same column. For this post we will be using a very simple HTML layout as follows-
<table>
<tr>
<th>data 1</th><th>data 2</th>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
</table>
For context menu we are going to use this plugin.

For content menu we are using the following HTML for the menu content, which include two options- copy and cancel. HTML for the context menu is as follows-
    <ul id="myMenu" class="contextMenu">
<li class="copy"><a href="#copy">Copy value</a></li>
<li class="quit separator"><a href="#cancel">Cancel</a></li>
</ul>
For implementing the context menu we need to take the following files references or we can download from the desired location-
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script src="http://labs.abeautifulsite.net/archived/jquery-contextMenu/demo/jquery.contextMenu.js"
type="text/javascript"></script>
<link href="http://labs.abeautifulsite.net/archived/jquery-contextMenu/demo/jquery.contextMenu.css"
rel="stylesheet" type="text/css" />
Now we can use following JavaScript code for copying/duplicating the data in a column-
    <script type="text/javascript">
$(document).ready(function () {
$("table input").contextMenu({
menu: 'myMenu'
}, function (action, el, pos) {
if (action == "copy") {
index = el.closest("tr").children().index(el.parent()[0]);
$("table tr").each(function (i, item) {
$(item).find("td:eq(" + index + ") input").val(el.val());
})
}
});
});
</script>

No comments:

Post a Comment