jquery - Add column to table with input boxes -
i want make dynamic table number of rows , columns can added table.i made success dynamically add rows problem adding column in table.for adding column want user give columnname column using window.prompt
.when click add column adding column(without textboxes) second column,i want add column(with textboxes , columnname) closest addcolumn
button.
here table
<table class="dynatable"> <thead> <tr> <th><button class="add">add</button></th> <th>id</th> <th>name</th> <th>col 3</th> <th>col 4</th> <th><button style="width: 100px; height: 25px" class="addcolumn">add column</button></th> </tr> </thead> <tbody> <tr class="prototype"> <td><button class="remove">remove</button> <td><input type="text" name="id[]" value="0" class="id" /></td> <td><input type="text" name="name[]" value="" /></td> <td><input type="text" name="col4[]" value="" /></td> <td><input type="text" name="col3[]" value="" /></td> </tr> </table>
and js is
/// <reference path="jquery-1.8.2.min.js" /> $(document).ready(function () { var id = 0; // add button functionality $("table.dynatable button.add").click(function () { id++; var master = $(this).parents("table.dynatable"); // new row based on prototype row var prot = master.find(".prototype").clone(); prot.attr("class", "") prot.find(".id").attr("value", id); master.find("tbody").append(prot); }); // remove button functionality $("table.dynatable button.remove").live("click", function () { $(this).parents("tr").remove(); }); $("table.dynatable button.addcolumn").click(function () { var columnname = window.prompt("enter column name", ""); if (columnname) { $('table').find('tr').each(function () { $(this).find('td').eq(0).after('<td></td>'); //$(this).closest('td').after('<td></td>'); }); } }); });
live demo jsfiddle
edit1:
before column adding : after adding column table should :
please see jsfiddle demo
try
$(document).ready(function () { var id = 0; // add button functionality $("table.dynatable button.add").click(function () { id++; var master = $(this).closest("table.dynatable"); // new row based on prototype row var prot = master.find("tr.prototype").clone(); prot.attr("class", "") prot.find(".id").attr("value", id); master.find("tbody").append(prot); }); // remove button functionality $("table.dynatable button.remove").live("click", function () { $(this).parents("tr").remove(); }); $("table.dynatable button.addcolumn").click(function () { var $this = $(this), $table = $this.closest('table') var columnname = window.prompt("enter column name", ""); $('<th>' + columnname +'</th>').insertbefore($table.find('tr').first().find('th:last')) var idx = $(this).closest('td').index() + 1; $('<td><input type="text" name="col' + idx + '[]" value="" /</td>').insertbefore($table.find('tr:gt(0)').find('td:last')) }); });
demo: fiddle
Comments
Post a Comment