Add delete row java script

Add delete row java script

Below demo is to show how to add input field dynamically by java script

  • To add and delete rows you could use below java script codeĀ and test it here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<SCRIPT>
        function addRowToTable(tableID) {

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name="checkbox[]";
            cell1.appendChild(element1);

            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;

            var cell3 = row.insertCell(2);
            var element2 = document.createElement("input");
            element2.type = "text";
            var length=(table.rows.length)-1;
            element2.name = "operationParameterses["+length+"].name";
            cell3.appendChild(element2);

        }

        function deleteRowFromTable(idOfTable) {
            try {
            var table = document.getElementById(idOfTable);
            var totalRowCount = table.rows.length;

            for(var i=0; i<totalRowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {
                    table.deleteRow(i);
                    i--;
                    totalRowCount--;
                    
                }
            }
            }catch(e) {}
        }

    </SCRIPT>
</head>
<body>

    <h2>User Details</h2>

    <input type="button" value="Add Rows" onclick="addRowToTable('tableId')" style="background: yellow;padding: 5px;">
    <input type="button" value="Delete Row" onclick="deleteRowFromTable('tableId')" style="background: yellow;padding: 5px;">
    <TABLE id="tableId" width="350px" border="5px">
        <TR>
            <TD ><INPUT type="checkbox" name="checkbox" /></TD>
            <TD>1</TD>
            <TD><INPUT type='text' name="operationParameterses[0].name" /></TD>
        </TR>
    </TABLE>

</body>
</html>
  • Open html file in any browser. You wil see below.Click Add Row button to add or Select check-box to and Click Delete Row to delete Row.

 

add

Leave a Reply

Your email address will not be published. Required fields are marked *