Sunday, December 6, 2015

insert and delete recored in html using javascript





Step : 1  HTML

<input type="text" id="txtName" placeholder="enter name" />
<input type="text" id="txtEmail" placeholder="enter email" />
<button class="default-btn btnGreen" onclick="insertRecord();">+</button>
<button class="delAll" onclick="deleteAll();"> Delete All </button>
<button class="clearAll" onclick="clearFields();"> Clear </button>
<table id="myTable"></table>

Step : 2  CSS

body{
     font-family: arial;
}

input{
     border: 1px solid #35AC19;
     color: #35AC19;
     padding: 2px 5px;
     height: 25px;
     width: 130px;
}

.default-btn{
     color: #FFF;
     width: 25px;
     height: 25px;
     text-align: center;
     font-weight: bold;
     border: 0;
     cursor: pointer;
}

.btnGreen{background-color: #35AC19;}

.btnRed{background-color:#D0131A;}

.delAll, .clearAll{
     text-align: center;
     border: 1px solid #35AC19;
     height: 25px;
     cursor: pointer;
     background-color: #35AC19;
     color: #FFF;
}

table{margin-top: 10px;}

table, th, td{
     border: 1px solid #888;
     border-collapse: collapse;
}

th, td{
     padding: 0px 15px;
     color: #35AC19;
}

table tr:nth-child(even){background-color: #F3F3F3;}

table tr td:last-child{padding: 2px;}


Step : 3  Javascript

function insertRecord(){
     var table = document.getElementById("myTable");
     var row = table.insertRow(0);
     var cell1 = row.insertCell(0);
     var cell2 = row.insertCell(1);
     var cell3 = row.insertCell(2);
             
     cell1.innerHTML = document.getElementById("txtName").value;
         
     cell2.innerHTML = document.getElementById("txtEmail").value;
         
     cell3.innerHTML = '<button class="default-btn btnRed" onClick="javascript:deleteRow(this);">X</button>';
}
     
function deleteRow(obj){
     var index = obj.parentNode.rowIndex;
     var table = document.getElementById("myTable");
     table.deleteRow(index);
}
     
function clearFields(){
     document.getElementById("txtName").value = "";
     document.getElementById("txtEmail").value = "";
}
     
function deleteAll(){
     var rowCount = myTable.rows.length;
         
     for(var i = rowCount - 1; i > -1 ; i--){
          myTable.deleteRow(i);
}
}


Hope you'll like it. Soon'll update live demo link with more tutorials and some updates.
Thanks


No comments:

Post a Comment

Copyright © www.sureshsharma.info All rights reserved