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
- how to add extra information in every row of autocomplete
- ASP checkbox 'checked' attribute always returning true
- How to append javascript block in a string into html?
- equal expression doesn't work as expected in JS
- fill in the blanks quiz
- How to remove a div with a changing id via Tampermonkey/Greasemonkey?
- Autocomplete is showing bullets beside the data
- Prevent child button triggering a jquery event assigned to a parent
- Stop flickering on hovering between divs of same class
- TinyMCE link and code popups in Bootstrap
- Replace special characters on a set with
- jquery: show a selected text on an input
- How to consolidate the multiple j query scripts I have on the page into one?
- Pass data to a jQuery modal
- jQuery on click a div showing error
- Hide and show a div based on a page loaded value
- Using dxautocomplete dynamically
- Simulate Mouse Click on dropdown
- jquery: auto scroll page, but allow for mousewheel, still scrolling
- Calculation is not calculating correctly
- How to Access when the table of column <td> tag contains `display:none` in javascript
- Angular 2: How to capture when browser restore/maximize
- jQuery/AJAX appends data to DIV rather than updating current results on second form submit
- toggleClass not working in IE or Edge
- How to remove dynamically added collapsible in JQM
- What is the proper way to identify if a value matches any key in the data of a jqGrid?
- How to set ranges based on the item selected from dropdown
- Swapping content of div, on click on image or iframe (Vimeo)
- Retrieving each variable posted by AJAX
- jQuery Autocomplete with Caching from a url based on other options
- Cannot read some part of CSS content
- How to display nested list data in tabulator
- Get XML from PHP to Jquery - XML tags
- jQuery search through table rows, hidden and visible
- Convert Map Coords into Percentage JS or jQuery
- Page doesn't reload after loading a video
- how to get input value from the ng-repeat to the controller
- data is not saving into database using cakephp 2.0
- Get values of dynamically created input elements
- contenteditable is not working with draggable feature
- changePage to call method in target page java script file
- global variable is not set in jquery
- Struts2 action not being called on page refresh
- JQuery tablesorter Ajax sorting
- Feeding a value from a textbox to a variable using jQuery
- JQuery autonumeric set does not work
- How to pass a variable in phtml/php file to js file?
- Rewriting javascript to jquery for multiple forms on a page
- jQuery DataTable Sort US Date String
- Reloading lightbox after ajax content loads
- JavaScript - Add img with data-pic
- Divide Canvas Arc To 364 Days
- Add «Load More» to data-output received with $.getJSON from Google Spreadsheet
- How to make pagination with Node, Mongoose, Bootstrap and pass it to html?
- fade in for background-color(button) and drop down menu superfish menu
- close button isn't working on popup window
- jQuery load function handling session timeouts
- How To apply CSS To a jQuery variable?
- Passing a variable value, rather than its name, as a class
- How can you use jQuery to change all the avatar images' src attribute on Twitter.com systematically?
- Strange syntactic behaviour
- Attach endpoint to a div drargged from a palette
- Kendo Calendar with two-four months view
- Change select option with checkbox checked and jQuery
- Refreshing multiple partials with polling in Rails
- Rateit plugin not working when used in Mustache.js template
- Javascript Array empty on Ajax call
- pass a var from one page to another
- Maximum call stack size exceeded when using select2 on appended select fields
- Getting an event from a combobox when selecting the same item
- jQuery each function for a group of elements (animate multiple selectors at the same time)
- Scroll bootstrap 3 modal
- Jump over like this example
- php jquery popup message box working in the while loop
- how can i call multiple ajax request after one request complete
- How do I delete and move later function arguments to the left if an object type is excluded?
- jquery deleting parent elements which are clones
- Cannot copy the color from textbox in Spectrum Colorpicker plugin when used inside Magnific Popup plugin
- javascript add new form
- Aframe device detection
- JQuery Cycle Plugin and CSS Sprite - no hover registered with Opera
- Formula calculator in jQuery
- Calling goto() externally/manually
- rails 6 Cannot find module 'jquery'
- Filter <SELECT> options based on value
- How to make AJAX working with select2?
- using :onkeyup=> for a f.text_field using jQuery
- Simulate mouse enter/out on array of divs with delay
- To change the icon upon click with angularJs
- Make a matrix with input inside a DIV by mixing input values
- Creating menu: replacing href with jQuery click & toggle function
- Disabling the Ability to Highlight Text in an Input
- How do you assign variables or work with numbers in forms created by php loops?
- Synchronise css keyframe animation with jQuery setInterval
- How to solve this ajax jquery error?
- z-index for button over jquery slider
- Jquery Accordion causing Multiline textbox behave abnormally
- How to refresh the table to initial state for new search in jquery?
- JQuery autocomplete return into multiple fileds
- Query prevent form on submit response back from php
- How to store object at a certain level in the JSON data by dynamically iterating through it?
- how to add multi captcha in same page and check both checkbox its fill
- jQuery qTip: set position in custom style
- Get total from table input as grand total in jquery
- Jquery - Can you stop a div from updating until action in div is done?
- Getting parent elements
- Jquery DataTable pagination Not working when postaback
- Datepicker stop working after appending HTML Form - AJAX response appending
- Jquery, dynamic remove table row issue
- jQuery.getJSON not working in IE with special characters
- Social Sharing Buttons Not Working in custom WordPress theme
- JQuery Validation + Repeater + Panel - Validation Issue
- Fullcalendar date range not showing events pass this year
- Spring mvc + ajax on Responsebody
- Accessing / Manipulating the Actual DOM With a Chrome Extension
- javascript send variable but insert array php not work propertly
- jquery ready handler never executed
- Jquery and AngularJS routes
- jQuery SerializeArray/Param get the class name?
- Limit for replace string with jQuery
- Bootstrap popover align in middle
- Select specific li element which start's with selected character
- Using this jQuery plugin (not mine) good coding practice?
- Check checkbox based on ajax response
- jquery adding elements using loop before page load
- Keep Space above a fixed background you scroll up
- TypeError: .offset(...) is undefined
- How to prevent strings getting cut at the # sign?
- When added to cells error and not working
- jquery ajaxStop event not working in IE9
- Capture all click events using jquery regardless of elements click event having stopPropagation
- Issue with removing cloned element once created
- Datepicker Eternicode - doesn't work
- Google analytics incorrect event reporting
- How to submit the form in focus
- Meteor - DOM queries not working if markup is nested in {{#with}} block
- HTML/CSS - shadow image resize
- How to add Arrows in Scroll Bar (Left - Right)
- Show newly data using Ajax and jQuery
- Print exception in Ajax thrown from PHP
- jquery datatables 1.10 dates sorting
- Alert Text When Input is Changed by Button
- Phantomjs: take screenshot of the current page?
- How can i show an asterisk (to indicate field is required) inside a select2 dropdown?
- Iterator inside HTML and JQuery for initializing a JQuery element
- jquery mobile button refresh not working programmatically
- keyboard friendly AJAX search
- Zoom a div when it reaches certain area on webpage
- Why do all of my JQuery drag and drop objects disappear when I try to drop them into each other?
- Jump to last slide on Bootstrap carousel