Accessing Data from a database and performing crud operation is an important step of any programming language.
Sometimes in our application, we need to perform insert, update and delete records(crud) in a Table using inline editing with the edit and delete icon. So in this example, we are going to create an HTML page. In which we will show the list of users using Json and then we will perform the crud operation in that using Json data.
let’s do that step by step.
In this, we will discuses the below point
- CRUD operation in JavaScript with validation
- Pure JavaScript CRUD operations with HTML
- CRUD operations using JSON in JavaScript
CRUD operations using JSON in JavaScript
In this post We will try to create a basic page where Users can see all the lists of records in a Table using json data with add button for adding new records in the table, edit button for updating existing records and delete button to delete any existing records from Json data and table. before adding the record in the Json array we are also performing the validation.
Html page
<!DOCTYPE html>
<html>
<head>
<title>CRUD operations using JSON in JavaScript</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>CRUD operations using JSON in JavaScript</h1>
<br />
<table class="table">
<thead>
<tr>
<th>CustomerId</th>
<th>CustomerName</th>
<th>CustomerEmail</th>
<th>Address</th>
</tr>
</thead>
<tbody id="tblbody">
</tbody>
</table>
</div>
</body>
</html>
<script type="text/javascript">
//json array
var customerArray = [
{
"id": 119447,
"customer_name": "Qa",
"customer_email": "sample604@gmail.com",
"address": "USA"
},
{
"id": 119443,
"customer_name": "Qa",
"customer_email": "sample938@gmail.com",
"address": "USA"
},
{
"id": 119437,
"customer_name": "Qa",
"customer_email": "sample12356777676@gmail.com",
"address": "USA"
},
{
"id": 119428,
"customer_name": "Maduwantha",
"customer_email": "sample12@gmail.com",
"address": "CAN"
},
{
"id": 119422,
"customer_name": "dhruvi",
"customer_email": "dhruvi@gmail.com",
"address": "usa"
},
{
"id": 119421,
"customer_name": "hasti",
"customer_email": "hasti@gmail.com",
"address": "usa"
},
{
"id": 119411,
"customer_name": "asdf",
"customer_email": "sakwiyamadaliqwt@gmail.com",
"address": "usa"
},
{
"id": 119409,
"customer_name": "csd",
"customer_email": "sakwiyamadalitsoaaa2azczax@gmail.com",
"address": "csd"
},
{
"id": 119385,
"customer_name": "asd",
"customer_email": "mike125lf3@gmail.com",
"address": "asd"
}
]
//bind json data to html table
bindjsondata();
function bindjsondata() {
document.getElementById('tblbody').innerHTML = "";
//iterate through each object in Json array and create row
customerArray.forEach(function (item, index) {
var btnEditId = "btnedit" + item.id;
var btnDeleteId = "btndelete" + item.id;
var tableRow = "<tr Id='" + item.id + "' data-CustomerID='" + item.id + "' data-CustomerName='" + item.customer_name + "' data-email='" + item.customer_email + "' data-Address='" + item.address + "'>"
+ "<td class='td-data'>" + item.id + "</td>"
+ "<td class='td-data'>" + item.customer_name + "</td>"
+ "<td class='td-data'>" + item.customer_email + "</td>"
+ "<td class='td-data'>" + item.address + "</td>"
+ "<td class='td-data'>" +
"<button id='" + btnEditId + "' class='btn btn-info btn-xs btn-editcustomer' onclick='showEditRow(" + item.id + ")'><i class='fa fa-pencil' aria-hidden='true'></i>Edit</button>" +
"<button id='" + btnDeleteId + "' class='btn btn-danger btn-xs btn-deleteCustomer' onclick='deleteCustomerRow(" + item.id + ")'><i class='fa fa-trash' aria-hidden='true'>Delete</button>"
+ "</td>"
+ "</tr>";
document.getElementById('tblbody').innerHTML += tableRow;
})
//add tr for adding record in the table at the bottom
var AddRow = "<tr>"
+ "<td class='td-data'></td>"
+ "<td class='td-data'><input type='text' id='txtCustomerName' placeholder='name..'></td>"
+ "<td class='td-data'><input type='email' id='txtemail' placeholder='email..'></td>"
+ "<td class='td-data'><input type='text' id='txtAddress' placeholder='address..'></td>"
+ "<td class='td-data'>" + "<button id= 'btnaddCustomer' onclick='addCustomer()' class='btn btn-success'> <i class='fa fa-plus-circle' aria-hidden='true'></i>Add</button>"+"</td>"
+ "</tr>";
document.getElementById('tblbody').innerHTML += AddRow;
}
function CreateUniqueCustomerID() {
//generate Unique number for Id
const ID = Date.now();
return ID;
}
function addCustomer() {
var customerID = CreateUniqueCustomerID();
var customerName = document.getElementById("txtCustomerName").value;
if (!customerName) {
alert('Please enter name!')
return false;
}
var email = document.getElementById("txtemail").value;
if (!email) {
alert('Please enter email!')
return false;
}
var emailfilter = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!emailfilter.test(email)) {
alert('Please enter a valid email address!');
return false;
}
var address = document.getElementById("txtAddress").value;
if (!address) {
alert('Please enter address!')
return false;
}
//creating object and push to json array
customerArray.push({
"id": customerID,
"customer_name": customerName,
"customer_email": email,
"address": address
});
document.getElementById('txtCustomerName').value = "";
document.getElementById('txtemail').value = "";
document.getElementById('txtAddress').value = "";
bindjsondata();
};
function showEditRow(CustomerID) {
//select tr of whose button was clicked
var CustomerRow = document.getElementById(CustomerID);
//returns array of all elements with class "row-data" in CustomerRow
var data = CustomerRow.querySelectorAll(".td-data");
var customerID = data[0].innerHTML;
var customerName = data[1].innerHTML;
var customeremail = data[2].innerHTML;
var address = data[3].innerHTML;
data[0].innerHTML = '<input name="txtupdate_CustomerID" disabled id="txtupdate_CustomerID" value="' + customerID + '"/>';
data[1].innerHTML = '<input name="txtupdate_CustomerName" id="txtupdate_CustomerName" value="' + customerName + '"/>';
data[2].innerHTML = '<input name="txtupdate_email" id="txtupdate_email" value="' + customeremail + '"/>';
data[3].innerHTML = '<input name="txtupdate_Address" id="txtupdate_Address" value="' + address + '"/>';
data[4].innerHTML =
"<button class='btn btn-primary btn-xs btn-updateCustomer' onclick='updateCustomers(" + customerID + ")'>" +
"<i class='fa fa-pencil' aria-hidden='true'></i>Update</button>"
+ "<button class='btn btn-warning btn-xs btn-cancelupdate' onclick='cancelUpdate(" + customerID + ")'><i class='fa fa-times' aria-hidden='true'></i>Cancel</button>"
+ "<button class='btn btn-danger btn-xs btn-deleteCustomer' onclick='deleteCustomerRow(" + customerID + ")'>"
+ "<i class='fa fa-trash' aria-hidden='true'></i>Delete</button>"
}
function cancelUpdate(CustomerID) {
var btneditId = "btnedit" + CustomerID;
var btndeleteId = "btndelete" + CustomerID;
//select tr of whose button was clicked
var CustomerRow = document.getElementById(CustomerID);
var data = CustomerRow.querySelectorAll(".td-data");
var customerName = CustomerRow.getAttribute("data-CustomerName");
var address = CustomerRow.getAttribute("data-Address");
var email = CustomerRow.getAttribute("data-email");
data[0].innerHTML = CustomerID;
data[1].innerHTML = customerName;
data[2].innerHTML = email;
data[3].innerHTML = address;
var actionbtn = "<button id='" + btneditId + "' class='btn btn-info btn-xs btn-editcustomer' onclick='showEditRow(" + CustomerID + ")'><i class='fa fa-pencil' aria-hidden='true'></i>Edit</button>" +
"<button id='" + btndeleteId + "' class='btn btn-danger btn-xs btn-deleteCustomer' onclick='deleteCustomerRow(" + CustomerID + ")'><i class='fa fa-trash' aria-hidden='true'>Delete</button>"
data[4].innerHTML = actionbtn;
}
function deleteCustomerRow(CustomerID) {
//remove object from json array
customerArray.splice(customerArray.findIndex(a => a.id === CustomerID), 1)
bindjsondata();
}
function updateCustomers(CustomerID) {
//select tr of whose button was clicked
var CustomerRow = document.getElementById(CustomerID);
var data = CustomerRow.querySelectorAll(".td-data");
var customerName = data[1].querySelector("#txtupdate_CustomerName").value;
var email = data[2].querySelector("#txtupdate_email").value;
var address = data[3].querySelector("#txtupdate_Address").value;
//Updating json object using filter
var customerObJ = customerArray.filter((x) => x.id == CustomerID).pop();
if (customerObJ != null) {
customerObJ.customer_name = customerName;
customerObJ.customer_email = email;
customerObJ.address = address;
}
bindjsondata();
}
</script>
In this, above we have taken a JSON array that contains an array of objects. JSON object has the id,customer_name,customer_email, and address keys.
Json array
var customerArray = [
{
"id": 119447,
"customer_name": "Qa",
"customer_email": "sample604@gmail.com",
"address": "USA"
},
{
"id": 119443,
"customer_name": "Qa",
"customer_email": "sample938@gmail.com",
"address": "USA"
},
{
"id": 119437,
"customer_name": "Qa",
"customer_email": "sample12356777676@gmail.com",
"address": "USA"
},
{
"id": 119428,
"customer_name": "Maduwantha",
"customer_email": "sample12@gmail.com",
"address": "CAN"
},
{
"id": 119422,
"customer_name": "dhruvi",
"customer_email": "dhruvi@gmail.com",
"address": "usa"
},
{
"id": 119421,
"customer_name": "hasti",
"customer_email": "hasti@gmail.com",
"address": "usa"
},
{
"id": 119411,
"customer_name": "asdf",
"customer_email": "sakwiyamadaliqwt@gmail.com",
"address": "usa"
},
{
"id": 119409,
"customer_name": "csd",
"customer_email": "sakwiyamadalitsoaaa2azczax@gmail.com",
"address": "csd"
},
{
"id": 119385,
"customer_name": "asd",
"customer_email": "mike125lf3@gmail.com",
"address": "asd"
}
]
On page load, we bind each JSON array into the HTML table with add, edit, and delete icon.Click on edit icon we are converting the table row into editable row with cancel and update option. so that user can also cancel the action.and onclick of update button we are updating json object using filter function.
In the present time, everybody is stressed over their vocation and everybody likewise needs that he ought to be at the level of his profession. For this, we really want the correct heading and course, yet it is more at when we are in our tutoring life.
Be that as it may, presently we are searching for courses in which we can lay out our best profession. For this, we are acquainting you with such a superior profession choices course, whose activity is expanding step by step. Web Designing in Hindi course is the most done course in the present time.
By following through with this tasks, you might not just make a decent profession choice at any point yet additionally bring in great cash.
The vast majority like to go about responsibilities in Government Sector or Private Sector, yet you can set up a decent foundation for yourself by taking a website composition course.
Web Designing In Hindi, there is a course of planning a site page of a site, in which numerous specialized terms are utilized, this cycle is called website composition.
As such, putting together website pages, content, content creation, content plan, page format, illustrations plan, and so on is called website architecture and it is likewise called the web advancement configuration process in specialized terms.
Any site or page is made with the assistance of HyperText Markup Language, whose truncation is HTML, it is a PC programming language whose design is through coding. Website specialists do a wonderful web architecture course utilizing HTML language to do website composition.
website composition assessment
A large portion of the sites are made with HTML and CSS which works Smoothly on the Browser.
As To Create New Website, Manage Graphics Design, Page Structure, Internal Designing of Website, Content Production, Site Maintenance, and so on. Which is a significant piece of it, which is instructed under the website composition course.
The post How to leave just points without lines in ChartJS 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 trigger event when an object is rearranged?
- Replacing form by sliding it
- Inserting a functional strongly-typed create view in a modal popup
- Append data to an html page with jQuery
- Drop elements into textbox html
- Owl Carousel 2 dynamically add videos
- 'Hovering' elements when clicked
- jQuery autocomplete dynamic ajax
- How to set same width for pictures in Lightbox?
- How to add more images to parallax image code
- Multiple document.ready not working how to combine them to make a single document.ready
- .NET MVC 4 website javascript function in popup window wouldn't run
- Getting an accurrate Results from Personality Test
- change width of an inner Iframe that is inside 2 divs
- Javascript function called inside onclick do not instantiate mongoose Model
- Javascript - How can I loop through the controls in a repeater and find the values of some dropdown lists
- Getting an error "Is null or not an object"
- How to handle Chrome rendering dynamically added elements with incomplete CSS
- Timed background color change
- (Drupal) How to only target elements within node with jQuery?
- Modal hidden in FF but not Chrome, IE11
- prettyPhoto - Light box not working
- Reload Images AND Thumbnails in jssor
- How to poll a local file and showing a div with jQuery based on result
- Disable click on other date (Datepicker without Jquery UI)
- Apply upload file plugin to jQueryUI button
- Wizard control inner table cellpadding need to reduce
- Getting webpage data to a JavaScript that can only run out of the webpage
- Fetching results using AJAX with Wordpress
- Elements Hiding When Clicked document jQuery
- How to set id for bootstrap tabs in javascript
- Retaining paragraphs with jquery.post
- lazyload jquery callback function
- Telerik Report Viewer don't work with jquery async: false
- Photo grid only displaying some images
- How to optimize this JavaScript/jQuery code?
- i can't get datetimepicker in my springmvc project
- jquery ajaxError post url to new page
- using javascript to do all div sizing to overcome browser support for vh, vm, and css calc
- how to get the value of an php array in jQuery
- Cookie redirection issue after submit (form)
- Running inner function once on window scroll
- Pressing enter key in rich:suggestionBox in IE causes SCRIPT16389: Unspecified error
- 404 Not Found Error comes up while sending post AJAX request to Laravel Controller
- jQuery ajax JSON dynamically adding inputs to form
- Display the name of the product inside the <h3> tag
- node automation for files move into another folder
- How do I get the name attribute of a hidden element within a div using jQuery?
- bootstrap columns not aligned in sync
- How to set correct xAxis time data in Highcharts?
- How rotate image and save it from JSP/Servlet page
- Stuck on IE7 accordion behaviour
- Change arrow accordion bootstrap with image
- JS/JQ Whack-A-Mole Game
- Cannot Retrieve User Input
- Click link to related slider item
- pure Javascript and jQuery conflict
- Can't get ajaxStop() / ajaxComplete() to work
- Mobile Safari - Autofocus not working
- 2 forms on same page - jquery context
- jQuery function evaluation timing
- .animate() not working more than once
- Yii ajax jquery multiple request just fist one works
- Animate a table row out in MeteorJS
- Load External JSON once, use it repeatedly....?
- How to display content on Mouseover in new row
- Dynamic Dropdown options based on Text box autocomplete in Laravel
- Jquery ajax is not sending cookie on IE9
- how to change default Bootstrap link hover color to custom color?
- Php CRUD app: using Ajax to delete row returns an entire page
- Location of JSON file within CodeIgniter for use as eventSource with fullCalendar jQuery plugin
- bigfoot.js and numbers with 2 characters
- ASP .Net MVC jQuery validation does not work on form submit but works onfocusout
- Javascript reading data from cross domain
- how to decrease the size of a image in bx slider to half
- Event handling for PanZoom.js not firing
- Dynamically created list needs links
- Uniformjs is disabled when an element is cloned
- jQuery event handler for input range on dynamic input (while sliding)
- scrollTo event overridden when using jQuery Mobile
- Toggle dropdown for each @item
- Jquery Focus-Out issue in IE on two textbox
- Upload multiple images one by one using AJAX after click submit
- How can I have a link on page 2 that opens page 1 and calls a javascript function on page 1?
- Accordion getting sporadically hidden in IE 7-8
- Dynamic Audio Player
- Coffeescript (jQuery) in Rails app doesn't work?
- Capture a snapshot of an upploaded video and save image.png file - JQUERY
- Text does not return to default when different toggle is closed
- Disable jQuery scrollbar plugin on touch devices?
- How can I use multiple versions of jQuery?
- Grabbing twitter feed in bootstrap slideshow
- JQuery pagination onPageClick event continuously running
- Infinite reload on Ajax Stop function
- jquery mask - query for the time input
- Ajax call not displaying message properly using Yii framework
- BackboneJS how to turn text URLs into clickable links
- Drag and Drop feature with Dropzone and want to include editable text field
- Jquery Portfolio Wordpress tags by category
- jquery append image is not loading
- jQuery - two events firing after Twitter Bootstrap's modal close
- Need help to understand this cookie script
- How to find a button with custom attribute
- Mac Safari 7 Rendering Issue scrollLeft() issue
- Need a way to disable HTML Frame on request
- HTML jquery collapsable tables
- How to add the disappearance of scroll (niceScroll)
- Getting element without id
- Wait to perform function until new data is reflected within the browser
- Sticky navigation bar doesn't work properly
- webkit css transition not working
- How to use jQuery to get data from a json_encode data in the php file?
- dynamically update select option on keyup in jquery
- How to retrieve data via jQuery AJX/JSON call and display error if validation fails
- How to refresh the bubbles content via ajax rather than refreshing entire bubble?
- Issues with series.data in highcharts
- Autocomplete ,How to manually generate search event
- Jquery Ajax page loads
- Jquery click function in a class pattern
- How to verify Dynamic drop down values in Selenium WebDriver?
- JQuery Add Multiple Re-sizable Divs on a button click
- How to call element.onload inside AJAX sucess function?
- How to use JQuery dialog as Confirm dialog in ASP.NET?
- Show Checkbox Values In Alert Box
- How to avoid the flash out caused by Javascript latency when page loading on Chrome?
- Jquery breaks within <object>
- Need to have lightbox thumbnail to resize when window shrinks
- POST / GET compared to submitting form to action page and loading result
- Space between div items gets exponentially larger with each new div
- jquery run away submit button
- Looking to switch Main image with selected thumbnail
- Remove change button in Jasny fileinput widget
- Using !important to a CSS change in JQuery - Using Bootstrap 3
- jquery validation plugin stops when remote
- How can I prevent the html loaded within my bootstrap modal from affecting my page html?
- Shopify getJSON API call to get the countryCode
- Best way to look up postcodes rails?
- How do I get the value of a JQuery plugin attribute so I can set it again?
- Creating a mobile-friendly widget on a non-mobile-friendly page
- Convert form into SearializeObject
- Linking 'Enter' key to button - not working
- js script displaying only true booleans from mysql database
- Replacing document.write with jQuery for conversion tracking code
- How to hide scroll bars from iframe?
- JS mouseOver on a single repeating element (with multiple class selectors)
- Chaining then() and accessing data in JavaScript
- OpenID in PHP Google App Engine
- Trying to build Home page for a website that contains a clickable image
- highlightSeries plugin for jquery flot charts
- How do i update a div tag after a ajax call?