Adding new Row into HTML Table in MVC using JQuery and Javascript


Introduction

This is the code snippet for adding a new row into html table using javascript. this code snippet trying to explain details by code for adding a new row into existing html table using java script.

Getting Started

Adding new row into existing html table is very easy. Here in this below code, first cloned an last row of existing table and later renamed the name property of all the child elements what this row contains. Again added this cloned row into the table
See the bellow code for details.

 $("#addNewDealer").click(function (e) {  
 e.preventDefault();  
 var $tabledockBody = $("#dealerdocs");  
 var $trdocLast = $tabledockBody.find("tr:last");  
 var $trNewdoc = $trdocLast.clone();  
 var suffix = $trNewdoc.find(':input:first').attr('name').match(/\d+/);  
 $trNewdoc.find('td:nth-child(3)').html('<input data-val="true" data-val-required="The ProofDoc field is required." name=[' + (parseInt(suffix) + 1) + '].ProofDoc type=file value>');  
 $trNewdoc.find('td:last').html('<a href="#" id=doc_' + (parseInt(suffix) + 1) + ' onclick="removeDocRow(doc_' + (parseInt(suffix) + 1) + ')" class="fa fa-times remove-list" data-toggle="tooltip" title="Remove"></a>');  
 $.each($trNewdoc.find(':input,select'), function (j, val) {  
 var olddN = $(this).attr('name');  
 var newdN = olddN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');  
 $(this).attr('name', newdN);  
 var olddid = $(this).attr('id');  
 if (olddid != undefined) {  
 var newid = olddid.replace(suffix + '_', (parseInt(suffix) + 1) + '_');  
 $(this).attr('id', newid);  
 }  
 var onc = $(this).attr('onchange');  
 if (onc != undefined) {  
 var nnc = onc.replace('documenttypechanged(' + suffix + ',this.value)', 'documenttypechanged(' + (parseInt(suffix) + 1) + ',this.value)')  
 $(this).attr('onchange', nnc);  
 }  
 try {  
 var type = $(this).attr('type');  
 if (type == 'text') {  
 $(this).val('');  
 }  
 if (type == 'hidden') {  
 $(this).val('0');  
 }  
 }  
 catch (err) {  
 alert(err);  
 }  
 $(this).removeClass("input-validation-error");  
 });  
 $trdocLast.after($trNewdoc);  
 try {  
 var from = $('form').removeData("validator");  
 form.removeData("unobtrusiveValidation");  
 }  
 catch (err) {  
 }  
 $("form").removeData("validator");  
 $("form").removeData("unobtrusiveValidation");  
 $.validator.unobtrusive.parse("form");  
 });  

Summary

Hope you have understood the code snippet, please give comment if you have any query

Thanks