<html>
<head>
<title>how to create crud operations(Insert,Update and delete) using JQuery.</title>
<script src="assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="includes/javascripts/jquery/jquery-ui.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
let i = 1;
$("#btnAdd").click(function () {
let newHtml = GetHtml().replace("$[Id]", i++).replace("$[Name]", $("#txtname").val()).replace("$[role]", $("#ddlRole option:selected").val()).replace("$[action]", "Edit").replace("$[Delete]", "Delete");
$("#table_td").append(newHtml);
});
$("#btnUpdate").click(function () {
let newHtml = GetHtml().replace("$[Id]", $("#txtId").val()).replace("$[Name]", $("#txtname").val()).replace("$[role]", $("#ddlRole option:selected").val()).replace("$[action]", "Edit").replace("$[Delete]", "Delete");
$("#table_td").append(newHtml);
$("#btnAdd").show();
$("#btnUpdate").hide();
$("#txtId").val('');
$("#txtname").val('');
$("#ddlRole option:selected").val('Select')
});
$(document).on("click", "#A_Edit", function () {
$("#btnAdd").hide();
$("#btnUpdate").show();
$("#txtId").show();
$("#txtId").val($(this).parent().parent().find('.Id').html());
$("#txtname").val($(this).parent().parent().find('.Name').html());
$("#ddlRole option:selected").val($(this).parent().parent().find('.role').html())
$(this).parents("tr").remove();
$("#btnUpdate").focus();
});
$(document).on("click", "#A_delete", function () {
$(this).parents("tr").remove();
});
});
function GetHtml() {
return "<tr><td class='Id'>$[Id]</td>"
+ "<td class='Name'>$[Name]</td>"
+ "<td class='role'>$[role]</td>"
+ "<td class='action'><a href='#' id='A_Edit'> $[action] </a> <a href='#' id='A_delete'>$[Delete]</a></td></tr>";
}
</script>
</head>
<body>
<form id="form1">
<table class='table table-bordered' id='UserInfo'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Action</th>
</tr>
<tbody id="table_td"></tbody>
</table>
<h3>
Add New
</h3>
<table class='table table-bordered' id='Add'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Role</th>
</tr>
<tr>
<td>
<input type="text" id="txtId" style="display: none" readonly name="ID" value="" />
</td>
<td>
<input type="text" id="txtname" name="name" value="" />
</td>
<td>
<select id="ddlRole">
<option value="Select">Select</option>
<option value="Admin">Admin</option>
<option value="Member">Member</option>
<option value="Vice-Admin">Vice-Admin</option>
</select>
</td>
</tr>
</table>
<input type="button" id="btnAdd" style="display: block" value="Add" />
<input type="button" id="btnUpdate" style="display: none" value="Update" />
<br />
<div id="output"></div>
</form>
</body>
</html>