In this article, we will learn how to perform CRUD operations using HTML, CSS, and javascript. On various blogs, you can find CRUD operations in javascript. But on many articles, I have noticed they are all using the static table to perform the insert update delete in HTML table using javascript.
But in this post, I will explain to you the insert, update, and delete function in the HTML table with the help of javascript.
In this article, We will cover the below points in the
- How to add data in HTML table dynamically using javascript
- Delete a particular row from a table in JavaScript
- How to edit selected row from HTML table using javascript
I have table Employees with column Employee Name, Employee Address, and PostalCode. With the click of add button, I’m adding the employee to the table and Now I want to perform a crud operation on this table using the javascript.
Html Page
<!DOCTYPE html> <html> <head> <title> Use of JQuery to Add Edit Delete Table Row </title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> </head> <body> <div class="container"> <h1> How to delete a particular row from a table in JavaScript </h1> <form id="addcustomerform"> <div class="form-group"> <label>Employee Name:</label> <input type="text" name="txtEmployeeName" id="txtEmployeeName" class="form-control" value="" required=""> </div> <div class="form-group"> <label>Employee Address:</label> <textarea class="form-control" name="txtAddress" id="txtAddress"></textarea> </div> <div class="form-group"> <label>PostalCode:</label> <input type="text" name="txtPostalCode" id="txtPostalCode" class="form-control" value="" required=""> </div> <button type="submit" id="btnaddEmployee" class="btn btn-primary save-btn">add Customer</button> </form> <br /> <fieldset> <legend>Employee List </legend> <table class="table"> <thead> <tr> <th>EmployeeId</th> <th>EmployeeName</th> <th>Address</th> <th>PostalCode</th> </tr> </thead> <tbody id="tblbody"> </tbody> </table> </fieldset> </div> </body> </html>
Javascript Code
<script type="text/javascript">
function CreateUniqueEmployeeID()
{
const ID = Date.now();
return ID;
}
document.getElementById("btnaddEmployee").addEventListener("click", function (event) {
event.preventDefault()
var EmployeeID = CreateUniqueEmployeeID();
var EmployeeName = document.getElementById("txtEmployeeName").value;
var Address = document.getElementById("txtAddress").value;
var PostalCode = document.getElementById("txtPostalCode").value;
var btneditId = "btnedit" + EmployeeID;
var btndeleteId = "btndelete" + EmployeeID;
var tablerow = "<tr Id='" + EmployeeID + "' data-EmployeeID='" + EmployeeID + "' data-EmployeeName='" + EmployeeName + "' data-Address='" + Address + "' data-PostalCode='" + PostalCode + "'>"
+ "<td class='td-data'>" + EmployeeID + "</td>"
+ "<td class='td-data'>" + EmployeeName + "</td>"
+ "<td class='td-data'>" + Address + "</td>"
+ "<td class='td-data'>" + PostalCode + "</td>"
+ "<td class='td-data'>" +
"<button id='" + btneditId + "' class='btn btn-info btn-xs btn-editcustomer' onclick='showeditrow(" + EmployeeID + ")'><i class='fa fa-pencil' aria-hidden='true'></i>Edit</button>" +
"<button id='" + btndeleteId + "' class='btn btn-danger btn-xs btn-deleteEmployee' onclick='deleteEmployeeRow(" + EmployeeID + ")'><i class='fa fa-trash' aria-hidden='true'>Delete</button>"
+ "</td>"
+ "</tr>";
debugger;
document.getElementById('tblbody').innerHTML += tablerow;
document.getElementById('txtEmployeeName').value = "";
document.getElementById('txtAddress').value = "";
document.getElementById('txtPostalCode').value = "";
});
function showeditrow(EmployeeID)
{
debugger;
var EmployeeRow = document.getElementById(EmployeeID); //this gives tr of whose button was clicked
var data = EmployeeRow.querySelectorAll(".td-data");
/*returns array of all elements with
"row-data" class within the row with given id*/
var EmployeeID = data[0].innerHTML;
var EmployeeName = data[1].innerHTML;
var Address = data[2].innerHTML;
var PostalCode = data[3].innerHTML;
var btneditId = "btnedit" + EmployeeID;
data[0].innerHTML = '<input name="txtupdate_EmployeeID" disabled id="txtupdate_EmployeeID" value="' + EmployeeID + '"/>';
data[1].innerHTML='<input name="txtupdate_EmployeeName" id="txtupdate_EmployeeName" value="' + EmployeeName + '"/>';
data[2].innerHTML='<input name="txtupdate_Address" id="txtupdate_Address" value="' + Address + '"/>';
data[3].innerHTML='<input name="txtupdate_PostalCode" id="txtupdate_PostalCode" value="' + PostalCode + '"/>';
data[4].innerHTML =
"<button class='btn btn-primary btn-xs btn-updateEmployee' onclick='updateemployees(" + EmployeeID + ")'>" +
"<i class='fa fa-pencil' aria-hidden='true'></i>Update</button>"
+ "<button class='btn btn-warning btn-xs btn-cancelupdate' onclick='cancelupdate(" + EmployeeID + ")'><i class='fa fa-times' aria-hidden='true'></i>Cancel</button>"
+ "<button class='btn btn-danger btn-xs btn-deleteEmployee' onclick='deleteEmployeeRow(" + EmployeeID + ")'>"
+ "<i class='fa fa-trash' aria-hidden='true'></i>Delete</button>"
}
function cancelupdate(EmployeeID)
{
debugger;
var btneditId = "btnedit" + EmployeeID;
var btndeleteId = "btndelete" + EmployeeID;
var EmployeeRow = document.getElementById(EmployeeID); //this gives tr of whose button was clicked
var data = EmployeeRow.querySelectorAll(".td-data");
var EmployeeName = EmployeeRow.getAttribute("data-EmployeeName");
var Address = EmployeeRow.getAttribute("data-Address");
var PostalCode = EmployeeRow.getAttribute("data-PostalCode");
data[0].innerHTML = EmployeeID;
data[1].innerHTML = EmployeeName;
data[2].innerHTML = Address;
data[3].innerHTML = PostalCode;
var actionbtn = "<button id='" + btneditId + "' class='btn btn-info btn-xs btn-editcustomer' onclick='showeditrow(" + EmployeeID + ")'><i class='fa fa-pencil' aria-hidden='true'></i>Edit</button>" +
"<button id='" + btndeleteId + "' class='btn btn-danger btn-xs btn-deleteEmployee' onclick='deleteEmployeeRow(" + EmployeeID + ")'><i class='fa fa-trash' aria-hidden='true'>Delete</button>"
data[4].innerHTML = actionbtn;
}
function deleteEmployeeRow(EmployeeID)
{
document.getElementById(EmployeeID).remove();
}
function updateemployees(EmployeeID)
{
var btneditId = "btnedit" + EmployeeID;
var btndeleteId = "btndelete" + EmployeeID;
var EmployeeRow = document.getElementById(EmployeeID); //this gives tr of whose button was clicked
var data = EmployeeRow.querySelectorAll(".td-data");
var EmployeeName = data[1].querySelector("#txtupdate_EmployeeName").value;
var Address = data[2].querySelector("#txtupdate_Address").value;
var PostalCode = data[3].querySelector("#txtupdate_PostalCode").value;
data[0].innerHTML = EmployeeID;
data[1].innerHTML = EmployeeName;
data[2].innerHTML = Address;
data[3].innerHTML = PostalCode;
var actionbtn = "<button id='" + btneditId + "' class='btn btn-info btn-xs btn-editcustomer' onclick='showeditrow(" + EmployeeID + ")'><i class='fa fa-pencil' aria-hidden='true'></i>Edit</button>" +
"<button id='" + btndeleteId + "' class='btn btn-danger btn-xs btn-deleteEmployee' onclick='deleteEmployeeRow(" + EmployeeID + ")'><i class='fa fa-trash' aria-hidden='true'>Delete</button>"
data[4].innerHTML = actionbtn;
}
</script>
*If you have any query please comment, we will reply to your query.
Some basic concept of JavaScript
Well, to understand it in simple words, we can say that JavaScript is not the main programming language but it is a scripting language. It is mainly used in browsers and it is used with HTML or CSS only. It has many features which we will know in the next article.
That’s why today I thought that why should you be given complete information about the use of JavaScript and what are its advantages to the people so that no other dilemma will arise in your mind. Then without delay let’s start and know about JavaScript
HTML It is used to define the content of web pages.CSS It is used to specify the layout of web pages.
Advantages of Javascript
- Speed. As long as external resources are needed, JavaScript is completely unhindered from network calls to a backend server.
- There is no need for it to be compiled on the client-side so that it gets some speed advantages.
- Simplicity. JavaScript is very simple to learn as well as to implement.
- Popularity. JavaScript is used throughout the web. Along with this, there are many resources on the internet to learn it as well. StackOverflow and GitHub are two great websites from where you can learn everything about Javascript.
- JavaScript can also be used within other scripts that have been written in different languages such as Perl and PHP.
- Server Load. Due to its use on the client-side, its demand in the website server decreases.
- Rich interfaces. Having drag, or drop components or sliders, provides a rich interface to your website.
- Versatility. Now JavaScript is also being used in many servers. JavaScript is used in the client’s server in the front-end, as well as now a complete JavaScript app can also be created from front to back with the help of JavaScript only.
Disadvantages of Javascript
- Client-Side Security. Since this code is executed from the computer of the users, so in some cases it can also be exploited for malicious purposes.
- Browser Support. While server-side scripts always produce the same type of output, the output of client-side scripts is a bit unpredictable.
Well, this is not a big problem because as long as they are working properly in big and popular browsers, then everything is safe.
The post Add edit and delete data in an HTML table using JavaScript appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Order of execution when using synchronous $.ajax call
- jQuery masonry example not working for me
- acts_as_votable javascript html table
- How to hide "maxlength" in html
- Best javascript event to listen for to to avoid affecting pagespeed hit?
- dynamic drop down how to show success using css (tic icon)
- jQuery if/else if statement doesn't work after the first "if"
- Get selected value of a dropdown's using jquery php
- Placeholder not working in IE 11 when set using Jquery
- Count down timer with jquery and php in foreach loop not showing correct times
- Responsive multi level menu not working
- how to add a C# string in javaScript as text popup
- Reading a local file a _second_ time using the html5 file reader API
- Referencing a drop down menu in jQuery from ASP.NET
- jQuery error in IE8 - $ undefined
- Nested on() vs. delegated on()
- Calling ASP.Net HTTP handler on click of checkbox in Rad Grid
- Disable jQuery Draggable after keyup
- call php function from javascript/jquery using ajax
- Datatables Throwing Invalid JSON Response
- how can i add popup to flags in highchart?
- How can I use jQuery to access an element that's stored in an array?
- Change body tag on page load for bootstrap 2.0
- assigning tablesorter filter value via javascript change event. works first time. on subsequent tries filter value reverts when executing update
- Jquery UI Checkboxes - Check category only if all subcategories are checked
- Populating data from JSON for drop downs
- How to fix bubble size (marker size) in canvasjs?
- Update Listboxes based on Ajax result with JQuery
- Setting CSS Expression using $.css() in JQuery
- How to stop JQuery UI Autocomplete from clearing previouse entries?
- check if element is user visible using boostrap
- jquery: How to prevent the firefox to prompt the save document popup window from ctr+s?
- Referencing an element within a has()?
- Twitter bootstrap model form validation
- Two buttons creating unique IDs using jQuery - for jQuery UI Sortable/Draggable
- Status Text under Progress Bar
- Why isn't this jquery window working?
- TypeError: a is undefined in json fill jqgrid
- Javascript Jquery - Dont close if child element is clicked
- Bootstrap 3 :navbar not working
- some trouble for my jquery code
- Change my php $_POST form to a proper js / jQuery, Ajax no refresh needed form
- Moving image to first position after hide other elements
- Autocomplete for dynamically added text boxes using Class Attribute
- Change font size according to length of text
- How Can I Disable "Pinch Zoom" in Foundation Framework?
- Append to a replaced element using jQuery
- navigation menu with jQuery
- Nested ajax function yielding no result when using POST and isset in PHP script
- Client side routing with Page.js and bootstrap tabs
- Unable to reject jquery deferred with a piped function if it was resolved by a previous pipe
- $.getJSON - display individual headers
- why is last-child not working in this example?
- How to keep delay of 10 seconds after each submit
- convert reponse of jquery ajax call (need to handle 404 error for gravtar) for getting gravatar into image source
- Include script from external file into html
- How to use jquery on HTML loaded after document.ready()
- Restrict the audio playback for only certain duration of time using jQuery
- how do i select a element within a div using jquery
- Not able to retrieve the body section from ajax response
- Strange jquery post problem, wrong post url is used
- How to delete inserted <span> on backspace?
- submitting form with jquery not working as expected
- Lost http:// prefix in jquery AJAX call
- jQuery mobile - switches pages when I submit form
- contenteditable = true stops working when javascript is applied
- Highcharts: Plot yAxis values starting from a specific range
- jQuery show() hide() with nested levels
- JQuery can't find select options by text
- Cookie gives probably wrong format back
- Highcharts Pie, slice first item in series
- Activate and Deactivate the Rails code hyperlink using JQuery
- Regex to find some pattern in javascript
- Put navbar-brand and nav-items on different rows in Bootstrap 4 navbar
- how do we make it such that when the user clicks on anywhere but the popup box, the popup box will close.
- how to create jquery plugin for Speedometer
- Jquery additional function not work - number adding side by side
- Why do I get "Illegal invocation" of this object?
- Receive events from multiple HTML5 videos
- Populate right side of HTML view on list click with data using EJS
- show html formatted text inside jquery dialog box on dialog button click
- jQuery image doesn't .explode
- td loses ext file style settings after jQuery display:none then display:table
- html syntax error in jQuery.ajax funciton?
- How to remove checkbox from array in angular js
- jquery stop event bubbling with live
- Translate text box data dynamically using google translate and jquery in c# asp.net
- Set textbox value which is dynamically added has display:none property in Jquery
- autocomplete() generating non-text output
- Why ONLY my cycle div's stopped working on my page?
- JQuery Validation <select> min depends on other field, not working
- input text control doesn't work on android google chrome
- For loop not finishing execution only some of the time
- break large public javascript functions into smaller private functions
- Laravel pagination with ajax and json
- How do you populate a HTML select box (drop down list) using jQuery from C# code behind
- Error in converting the json value using JQuery
- jQuery iframe not able to set youtube url
- How to prevent CSS from changing when another tab(link) is clicked and the user is remaining on the same page?
- Dynamic Content Issue with Contact Form
- Numeric validation with jQuery
- Simplify repeating Jquery function
- Select element and add class [selected] to different element while removing the class [selected] from all others
- How to parse this JSON containing single array
- list of international number formats
- jquery validation to highlight only the label
- How to get all sibling elements of td into an array
- Loading Bootstrap Modal with onclick function
- Deselect value in Jquery Datepicker?
- Parent's mouseout is triggered when mouse enters parent from child
- Add buttons to webpage with Chrome Extension
- jQuery Not Working in IE11 On Live Server
- fix a div to the bottom of the 100% container and allow the while container to scroll
- How can I make a js function generic to work everywhere on my form? (DRY)
- How can i change this weather forecast widget position on my website?
- jQuery Pluggin. Adding both options and callback function
- how does $.post know what data to return?
- Wordpress core color picker (iris) in widget - refresh when edited in wordpress customizer
- jQuery Cycle2 possible change use multi-transitions
- Simple sitemap using Jquery
- How to define success handler in jquery?
- How to solve my jquery plugin issue?
- How to stop page refresh in asp.net on ajax call?
- jQuery show and fadeIn
- Hiding the nav-bar, while opening in the new window
- Once Appended unable to change .CSS Position
- Make the draggable item fade away when dropped onto droppable contianer
- Add/Remove Fields on Form
- Creating new dropdown lists with a button
- Button click function is not working
- Controlling AJAX requests
- if statement giving opposite result on ajax success
- jQuery string replace using regex
- Wordpress adding jQuery full Calendar support to wordpress
- Vertically scrollable and horizontally draggable divs on mobile
- slideToggle div by ID in Class
- Jquery click function only seems to be working once
- Reload a div on AJAX request
- im trying to make a music player but my buttons are not working
- Loading JSON values into their respective HTML elements
- Disable an input on submit
- why i can't use javascript function created inside jquery object and how to declare custom function in jquery?
- How to detect if the element after a link is a span
- What does datatable.columns().search().draw() requests or posts in server-side php?
- How can I create an active tab effect in Jquery depending on the page I'm on?
- JQuery toggle class plus animation
- Cannot read property 'minDate' of undefined
- get previous page "pagecontainer transition"
- Jsplump dynamically draw state machine diagram
- How to pass data from vue component to view(HTML) in laravel