Wednesday, March 11, 2015

Add and Remove HTML table rows dynamically in Javascript

Add and Remove HTML table rows dynamically in Javascript
<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script type="text/javascript">
        $(document).ready(function () {
            var cnt = 2;
            $("#add_row").click(function () {
                $('#tbl1 tr').last().after(
                '<tr id="tr' + cnt + '">' +
                '<td><input type="checkbox" name="cb_Items" id="cb' + cnt + '"></td>' +
                '<td><input type="text" name="txtbx' + cnt + '" value="' + cnt + '"></td>' +
                '</tr>');
                cnt++;
            }); 
            $("#remove_row").click(function () {
                if ($('#tbl1 tr').size() > 1) {

                    var rows = document.getElementsByName('cb_Items');
                    var selectedRows = [];
                    for (var i = 0, l = rows.length; i < l; i++) {
                        if (rows[i].checked) {
                            selectedRows.push(rows[i].id.substr(rows[i].id.length - 1));
                        }
                    }
                    for (var j = 0; j < selectedRows.length; j++) {
                        $("#tbl1 #tr" + selectedRows[j]).remove();
                    }
                }
            });
        });
    </script> 
</head> 
<body>
    <a href="javascript:void(0);" id='add_row'>Add Row</a>
    <a href="javascript:void(0);" id='remove_row'>Remove Row</a>
    <table id="tbl1" border="1">
        <tr id="tr1">
            <td>
                <input type="checkbox" name="cb_Items" id="cb1"></td>
            <td>
                <input type="text" name="txtbx1" value="1" id="txt1"></td>
        </tr>
    </table>
</body>
</html>
Thank You.

Featured Post

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management https://docs.microsoft.com/en-us/azure/api-management/api-...

Popular posts