$(function() {
$("#showMovies").click(function() {
$.ajax({
method: "GET",
url: "http://localhost:3000/movielist",
dataType: "json",
success: function(response) {
$.each(response, function(i, movie) {
const rowText = "<tr>" +
"<td>" + movie.idmovielist + "</td>" +
"<td>" + movie.name + "</td>" +
"<td>" + movie.thumbnail_path + "</td>" +
"<td>" + movie.description + "</td>" +
"<td>" + movie.year_released + "</td>" +
"<td>" + movie.language_released + "</td>" +
"<td>" + "<button button id = \"deleteMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Delete</button>" + "</td>" +
"<td>" + "<button button id = \"editMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Edit</button>" + "</td>";
$("#movies").append(rowText);
});
}
});
});
$("#movieAdded").click(function(a) {
let mydata = {
idmovielist: $($("#newForm")[0].intNum).val(),
name: $($("#newForm")[0].name).val(),
thumnail_path: $($("#newForm")[0].thumnail_path).val(),
description: $($("#newForm")[0].description).val(),
year_released: $($("#newForm")[0].year_released).val(),
language_released: $($("#newForm")[0].language_released).val(),
}
displayMovie(mydata);
$("#newForm").trigger("reset");
$("#newForm").toggle();
a.preventDefault();
});
function displayMovie(data) {
$.ajax({
method: "POST",
url: "http://localhost:3000/movielist/addMovie",
dataType: "json",
data: data,
success: function(data) {
console.log(data);
}
});
}
$.ajax({
method: "DELETE",
url: "http://localhost:3000/movielist/5",
dataType: "json",
success: function(data) {
$.each(data, function(i, movie) {
const rowText = "<tr>" +
"<td>" + movie.idmovielist + "</td>" +
"<td>" + movie.name + "</td>" +
"<td>" + movie.thumbnail_path + "</td>" +
"<td>" + movie.description + "</td>" +
"<td>" + movie.year_released + "</td>" +
"<td>" + movie.language_released + "</td>" +
"<td>" + "<button button id = \"deleteMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Delete</button>" + "</td>" +
"<td>" + "<button button id = \"editMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Edit</button>" + "</td>";
$("#movies").append(rowText);
});
}
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
table {
background-color: lightblue;
}
tbody {
font-family: inherit;
}
html {
background-color: lightblue;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="mystyle.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="mycrud.js"></script>
</head>
<body>
<title>My Movies</title>
<header>
<h1>Movies</h1>
<button id="showMovies" type="button" class="btn btn-primary" data-toggle="modal" data-target=#exampleModal>All Movies</button>
</header>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="newForm">
<div class="form-group row">
<label for="idmovielist" class="col-sm-2 col-form-label">idmovielist</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="intNum" placeholder="idmovielist">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" placeholder="name">
</div>
</div>
<div class="form-group row">
<label for="thumnail_path" class="col-sm-2 col-form-label">thumnail_path</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="thumnail_path" placeholder="thumnail_path">
</div>
</div>
<div class="form-group row">
<label for="description" class="col-sm-2 col-form-label">description</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="description" placeholder="description">
</div>
</div>
<div class="form-group row">
<label for="year_released" class="col-sm-2 col-form-label">year_released</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="year_released" placeholder="year_released">
</div>
</div>
<div class="form-group row">
<label for="language_released" class="col-sm-2 col-form-label">language_released</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="language_released" placeholder="language_released">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="movieAdded" type="button" class="btn btn-primary" data-toggle="modal" data-target=#exampleModal>Add</button>
</div>
</form>
</div>
</div>
</div>
</div>
<button id="movieAdded" type="button" class="btn btn-primary" data-toggle="modal" data-target=#exampleModal>Add</button>
<table class="table table-bordered table-hover" width="100%">
<thead style="background-color:#ddd;" class="table-borderless">
<tr>
<th>idmovielist</th>
<th>name</th>
<th>thumnail_path</th>
<th>description</th>
<th>year_released</th>
<th>language_released</th>
<th>Action</th>
</tr>
</thead>
<tbody id="movies">
</tbody>
</table>
</header>
</body>
</html>
So above is my html css and java-script and also I have a screen shot of my UI I have did a post request back-end and I also executed it in the front end as well when I click the add button the modal form pops up on what things I want to add is there a way I could do a post request only on front end with out having to go back to back end and changing it every-time
app.post('/movielist/addMovie',(req, res) => {
mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('64','DudeLove','wfburfr.jpg','silly','2019','english')",
req.body,
(err,rows) => {
if (!err) {
res.send("Movie is added");
} else {
console.log(err);
}
});
});
above is the code of my back end I did and is you see in the Ui the result is their but if I want to add more movies is there a way I could just add movies in the front end with out having to go back all the time to the back end to change it
As You are using POST method, you have to pass the params in the POST's body and read them on the serverside.
Your clientside is correct - you pass data to the server.
$.ajax({
method: "POST",
url: "http://localhost:3000/movielist/addMovie",
dataType: "json",
data: data,
success: function(data) {
console.log(data);
}
});
On the serverside you read POST body data elements using req.body.PARAMNAME;
As You've passed them as JSON, they will be parsed already.
So now you just put those values into the query dynamically:
"INSERT INTO movielist (`idmovielist`,`name`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"')",
OF COURSE you should escape the strings for SQL injections first. And ID probably shouldn't be passed, but auto-incremented in the database.
mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('64','DudeLove','wfburfr.jpg','silly','2019','english')",
You've hard-coded the values to be inserted into your query.
Don't do that. Read the values from the POST request.
Related
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 4 months ago.
i know it's a question asked many times here, but i tried all the solutions and no one is working.
I want to change the output in my CRUD from the input form to dd/mm/yyyy and not in yyyy-mm-dd.
Here's my code:
var nextId = 1;
var activeId = 0;
function productDisplay(ctl) {
var row = $(ctl).parents("tr");
var cols = row.children("td");
activeId = $($(cols[0]).children("button")[0]).data("id");
$("#productname").val($(cols[1]).text());
$("#introdate").val($(cols[2]).text());
$("#finishdate").val($(cols[3]).text());
$("#url").val($(cols[4]).text());
$("#phone").val($(cols[5]).text());
$("#note").val($(cols[6]).text());
$("#client").val($(cols[7]).text());
$("#updateButton").text("Aggiorna");
}
function productUpdate() {
if ($("#updateButton").text() == "Add") {
productUpdateInTable(activeId);
}
else {
productAddToTable();
}
formClear();
$("#productname").focus();
}
function productAddToTable() {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(
productBuildTableRow(nextId));
nextId += 1;
}
function productUpdateInTable(id) {
var row = $("#productTable button[data-id='" + id + "']")
.parents("tr")[0];
$(row).after(productBuildTableRow(id));
$(row).remove();
formClear();
$("#updateButton").text("Add");
}
function productBuildTableRow(id) {
var ret =
"<tr>" +
"<td>" +
"<button type='button' " +
"onclick='productDisplay(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-pencil' />" +
"</button>" +
"</td>" +
"<td>" + $("#productname").val() + "</td>" +
"<td>" + $("#introdate").val() + "</td>" +
"<td>" + $("#finishdate").val() + "</td>" +
"<td>" + $("#url").val() + "</td>" +
"<td>" + $("#phone").val() + "</td>" +
"<td>" + $("#note").val() + "</td>" +
"<td>" + $("#client").val() + "</td>" +
"<td>" +
"<button type='button' " +
"onclick='productDelete(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-minus' />" +
"</button>" +
"</td>" +
"</tr>"
return ret;
}
function productDelete(ctl) {
var result = confirm("Want to delete record?");
if (result) {
var result2 = confirm("Really?");
}
if (result2) {
$(ctl).parents("tr").remove();
}
}
function formClear() {
$("#productname").val("");
$("#introdate").val("");
$("#finishdate").val("");
$("#url").val("");
$("#phone").val("");
$("#note").val("");
$("#client").val("");
}
function doSearch(text, color = "yellow") {
if (color != "transparent") {
doSearch(document.getElementById('hid_search').value, "transparent");
document.getElementById('hid_search').value = text;
}
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<h2><b>Availability</h2></b>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="col-sm-0">Modify</th>
<th class="col-sm-2">Name</th>
<th class="col-sm-1">From</th>
<th class="col-sm-1">To</th>
<th class="col-sm-2">Area</th>
<th class="col-sm-2">Phone</th>
<th class="col-sm-3">Note</th>
<th class="col-sm-2">Client</th>
<th class="col-sm-0">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
Add Availability
</div>
<div class="panel-body">
<div class="form-group">
<label for="productname">
Name
</label>
<input type="text" class="form-control" value="" id="productname" />
</div>
<div class="form-group">
<label for="introdate">
From
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="introdate">
</div>
<div class="form-group">
<label for="introdate">
To
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="finishdate" />
</div>
<div class="form-group">
<label for="area">
Area
</label>
<input type="search" class="form-control" value="" id="url" />
</div>
<div class="form-group">
<label for="phone">
Phone
</label>
<input type="" class="form-control" value="" id="phone" />
</div>
<div class="form-group">
<label for="note">
Note
</label>
<input type="" class="form-control" value="" id="note" />
</div>
<div class="form-group">
<label for="client">
Client
</label>
<select id="client" class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-xs-12">
<button type="button" id="updateButton" class="btn btn-primary" onclick="productUpdate();">
Add
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When I insert a new record from form field date, the output in my CRUD is like YYYY-MM-DD.
This should help you. Pass a valid date in any format and the function will return a dd/mm/yyyy date format
// Helper function to format date from $(input).val()
function formatDate(date) {
if (date == '') {
return '';
}
let d = new Date(date),
ye = new Intl.DateTimeFormat('en', {
year: 'numeric'
}).format(d),
mo = new Intl.DateTimeFormat('en', {
month: '2-digit'
}).format(d),
da = new Intl.DateTimeFormat('en', {
day: '2-digit'
}).format(d);
return (`${da}-${mo}-${ye}`);
}
// ----
var nextId = 1;
var activeId = 0;
function productDisplay(ctl) {
var row = $(ctl).parents("tr");
var cols = row.children("td");
activeId = $($(cols[0]).children("button")[0]).data("id");
$("#productname").val($(cols[1]).text());
$("#introdate").val($(cols[2]).text());
$("#finishdate").val($(cols[3]).text());
$("#url").val($(cols[4]).text());
$("#phone").val($(cols[5]).text());
$("#note").val($(cols[6]).text());
$("#client").val($(cols[7]).text());
$("#updateButton").text("Aggiorna");
}
function productUpdate() {
if ($("#updateButton").text() == "Add") {
productUpdateInTable(activeId);
}
else {
productAddToTable();
}
formClear();
$("#productname").focus();
}
function productAddToTable() {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(
productBuildTableRow(nextId));
nextId += 1;
}
function productUpdateInTable(id) {
var row = $("#productTable button[data-id='" + id + "']")
.parents("tr")[0];
$(row).after(productBuildTableRow(id));
$(row).remove();
formClear();
$("#updateButton").text("Add");
}
function productBuildTableRow(id) {
var ret =
"<tr>" +
"<td>" +
"<button type='button' " +
"onclick='productDisplay(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-pencil' />" +
"</button>" +
"</td>" +
"<td>" + $("#productname").val() + "</td>" +
"<td>" + formatDate($("#introdate").val()) + "</td>" + // call helper function
"<td>" + formatDate($("#finishdate").val()) + "</td>" + // call helper function
"<td>" + $("#url").val() + "</td>" +
"<td>" + $("#phone").val() + "</td>" +
"<td>" + $("#note").val() + "</td>" +
"<td>" + $("#client").val() + "</td>" +
"<td>" +
"<button type='button' " +
"onclick='productDelete(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-minus' />" +
"</button>" +
"</td>" +
"</tr>"
return ret;
}
function productDelete(ctl) {
var result = confirm("Want to delete record?");
if (result) {
var result2 = confirm("Really?");
}
if (result2) {
$(ctl).parents("tr").remove();
}
}
function formClear() {
$("#productname").val("");
$("#introdate").val("");
$("#finishdate").val("");
$("#url").val("");
$("#phone").val("");
$("#note").val("");
$("#client").val("");
}
function doSearch(text, color = "yellow") {
if (color != "transparent") {
doSearch(document.getElementById('hid_search').value, "transparent");
document.getElementById('hid_search').value = text;
}
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<h2><b>Availability</h2></b>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="col-sm-0">Modify</th>
<th class="col-sm-2">Name</th>
<th class="col-sm-1">From</th>
<th class="col-sm-1">To</th>
<th class="col-sm-2">Area</th>
<th class="col-sm-2">Phone</th>
<th class="col-sm-3">Note</th>
<th class="col-sm-2">Client</th>
<th class="col-sm-0">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
Add Availability
</div>
<div class="panel-body">
<div class="form-group">
<label for="productname">
Name
</label>
<input type="text" class="form-control" value="" id="productname" />
</div>
<div class="form-group">
<label for="introdate">
From
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="introdate">
</div>
<div class="form-group">
<label for="introdate">
To
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="finishdate" />
</div>
<div class="form-group">
<label for="area">
Area
</label>
<input type="search" class="form-control" value="" id="url" />
</div>
<div class="form-group">
<label for="phone">
Phone
</label>
<input type="" class="form-control" value="" id="phone" />
</div>
<div class="form-group">
<label for="note">
Note
</label>
<input type="" class="form-control" value="" id="note" />
</div>
<div class="form-group">
<label for="client">
Client
</label>
<select id="client" class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-xs-12">
<button type="button" id="updateButton" class="btn btn-primary" onclick="productUpdate();">
Add
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I am working on a project in that there is a requirement of dynamically generate html elements, one is date-picker and another one is time range, and it should generate dynamically whenever i click on add row for date-picker and for multiple time ranges.
Can anyone help me how to do this?
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/css/bootstrap-timepicker.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.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/js/bootstrap-timepicker.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12"> </div>
<div class="col-md-12"> </div>
<div id="date-selection">
<div class="row" id="date_count_0">
<div class="col-md-12"> </div>
<div class="col-md-11">
<input type="text" name="date[0]" value="" class="form-control datepicker"/>
</div>
<div class="col-md-1" style="text-align: right;">
<i class="fa fa-plus"></i>
</div>
<div class="col-md-12"> </div>
<div class="col-md-12"> </div>
<div class="timing-selection_0">
<div class="col-md-12">
<div class="row">
<div class="col-md-5">
<input type="text" name="dat[0][from]" value="" class="form-control time-picker" />
</div>
<div class="col-md-5">
<input type="text" name="dat[0][to]" value="" class="form-control time-picker" />
</div>
<div class="col-md-2" style="text-align: right;">
<a href="javascript:void(0);" class="btn btn-info add_timings" id="add_timings_0" data-id="0" onclick="add_timings(this)">
<i class="fa fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var date_count = 1;
var time_count = 1;
function add_timings(attr){
var thisid = $(attr).data("id");
var inner_timings = "<div id='delete_timing_" + time_count + "'><div class='col-md-12'> </div>" +
"<div class='col-md-12'>" +
"<div class='row'>" +
"<div class='col-md-5'>" +
"<input type='text' name='dat[" + thisid + "][from]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-5'>" +
"<input type='text' name='dat[" + thisid + "][to]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-2' style='text-align: right;'>" +
"<a href='javascript:void(0);' class='btn btn-info add_timings' id='add_timings_" + time_count + "' onclick='deletetimings(" + time_count + ")'>" +
"<i class='fa fa-minus'></i>" +
"</a> " +
"</div>" +
"</div>" +
"</div>" +
"</div>";
$(".timing-selection_" + thisid).append(inner_timings);
$('.time-picker').timepicker({
template: false,
showInputs: false,
minuteStep: 5
});
time_count++;
}
$("#add_date").on("click", function (row, index) {
var texttoappend = "<div id='delete_row_" + date_count + "'>" +
"<div class='row'>" +
"<div class='col-md-12'> </div>" +
"<div class='col-md-11'>" +
"<input type='text' name='date[" + date_count + "]' value='' class='form-control datepicker' /> " +
"</div>" +
"<div class='col-md-1' style='text-align: right;'>" +
"<a href='javascript:void(0);' class='btn btn-info' onclick='delete_date(" + date_count + ");'><i class='fa fa-minus'></i></a>" +
"</div>" +
"<div class='col-md-12'> </div>" +
"<div class='col-md-12'> </div>" +
"<div class='timing-selection_" + date_count + "'>" +
"<div class='col-md-12'>" +
"<div class='row'>" +
"<div class='col-md-5'>" +
"<input type='text' name='date[" + date_count + "][from]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-5'>" +
"<input type='text' name='date[" + date_count + "][to]' value='' class='form-control time-picker' /> " +
"</div>" +
"<div class='col-md-2' style='text-align: right;'>" +
"<a href='javascript:void(0);' class='btn btn-info add_timings' id='add_timings_"+date_count+"' data-id='"+date_count+"' onclick='add_timings(this)'>"+
"<i class='fa fa-plus'></i>"+
"</a>" +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</div>";
"</div>";
$("#date-selection").append(texttoappend + "<br />");
date_count++;
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
});
$('.time-picker').timepicker({
template: false,
showInputs: false,
minuteStep: 5
});
});
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
});
$('.time-picker').timepicker({
template: false,
showInputs: false,
minuteStep: 5
});
function delete_date(datecount) {
$("#delete_row_" + datecount).remove();
}
function deletetimings(datecount) {
$("#delete_timing_" + datecount).remove();
}
</script>
</body>
</html>
I have small project where I need to be able to insert/edit/delete records from JSON file. I use http://myjson.com/ API for this project (not sure if this is the best solution maybe some other sources API's are better). I'm trying to remove record from json file and I'm not sure how to do that. Is there any way to do that with this API? There are instructions on how to add/update records to the json file but none on how to remove record. Here is my code example:
var contactStorage = {};
/*** Start: Build Datatables function. ***/
function buildDataTable(tblID, columnsArray, displayLength) {
$('#' + tblID).DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"iDisplayLength": displayLength,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': columnsArray
}],
"language": {
"emptyTable": "No records were found."
}
});
}
/*** End: Build Datatables function. ***/
/*** Start: Phone number format for US standard. ***/
$('.us-phone').on("keypress", formatPhoneUS);
function formatPhoneUS(e) {
var output,
inputVal = $(this).val().replace(/[^0-9]/g, ''),
area = inputVal.substr(0, 3),
pre = inputVal.substr(3, 3),
tel = inputVal.substr(6, 4);
if (parseInt(inputVal, 10)) {
if (area.length < 3) {
output = "(" + area;
} else if (area.length === 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length === 3 && pre.length === 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
}
if (e.key === 'Backspace') return;
$(this).val(output);
};
/*** End: Phone number format for US standard. ***/
$("#frm_find").on("submit", findContacts);
function findContacts(e) {
e.preventDefault();
var frmFilter = $("#frm_filterby").val();
if (frmFilter) {
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/7iig8?' + new Date().getTime(),
dataType: 'json'
}).done(function(obj) {
contactStorage = obj.filter(function(entry) {
switch (frmFilter) {
case '1':
return entry.status === 1;
break;
case '2':
return entry.status === 0;
break;
default:
return entry;
}
});
showContacts(contactStorage);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
});
}
}
function showContacts(contactStorage) {
var contactsTbl = "<table id='contactsTbl' class='table table-bordered'><thead><tr><th>Last</th><th>First</th><th>Email</th><th>Phone</th><th>Status</th><th class='text-center'>Edit</th><th class='text-center'>Delete</th></tr></thead><tbody>";
if (contactStorage) {
for (var key in contactStorage) {
contactsTbl += "<tr id='" + $.trim(contactStorage[key].id) + "'><td>" + $.trim(contactStorage[key].last) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].first) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].email) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].phone) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].status === 1 ? 'Active' : 'Inactive') + "</td>";
contactsTbl += "<td class='text-center'><button class='btn btn-default btn-sm contact_edit' data-toggle='collapse' data-target='#save_contact,#search_contact'><span class='glyphicon glyphicon-edit'></span></button></td>"
contactsTbl += "<td class='text-center'><button class='btn btn-default btn-sm contacts_delete'><span class='glyphicon glyphicon-remove'></span></button></td></tr>";
}
}
contactsTbl += "</tbody></table><div class='row'><div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'><div id='contact_message' class='alert message-submit'></div></div></div>";
$('#contacts_list').empty().append(contactsTbl).show();
buildDataTable('contactsTbl', [5, 6], 10);
}
var deleteID, targetTr;
$("#contacts_list").on("click", ".contacts_delete", displayContact);
function displayContact() {
deleteID = $(this).closest('tr').attr('id'), // Get record ID.
targetTr = $(this).parents('tr');
var lastName = targetTr.find("td").eq(0).text(),
firstName = targetTr.find("td").eq(1).text(),
bodyContent = $('<p>You are about to delete record for <b>' + lastName + ', ' + firstName + '</b>.<p>Do you want to proceed?</p>');
$('#delete_modalBody').empty().append(bodyContent); // Append elements to body content.
$('#deleteModal').modal('show'); // Show delete modal box.
}
$("#deleteModal").on("click", ":button.confirm_delete", removeContact);
function removeContact() {
if (deleteID) {
var table = $("#contactsTbl").DataTable(); // Select DataTable by ID.
table.row(targetTr).remove().draw(); // Remove record from DataTable.
delete contactStorage[deleteID]; // Remove element from JS object.
$("#contact_message").show().addClass("alert-success").html("Record successfully removed.").delay(5000).fadeOut('slow').queue(function() {
$(this).removeClass("alert-success").dequeue();
});
} else {
$("#contact_message").show().addClass("alert-danger").html("Error! Please contact your administrator.").delay(5000).fadeOut('slow').queue(function() {
$(this).removeClass("alert-danger").dequeue();
});
}
}
div.container {
padding-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Application</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- *** Start: JS and CSS for DataTables. *** -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />
<!-- *** End: JS and CSS for DataTables. *** -->
<link rel="stylesheet" type="text/css" href="App.css" />
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">Welcome to Contact Application</div>
<div class="panel-body">
<div id="search_contact" class="collapse in">
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#save_contact,#search_contact">
<span class="glyphicon glyphicon-plus-sign"></span> New Contact
</button>
</div>
</div>
<form name="frm_find" id="frm_find" autocomplete="off">
<div class="row find-row">
<div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
<select class="form-control" name="frm_filterby" id="frm_filterby" required>
<option value="">--Choose--</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
<option value="3">Show All</option>
</select>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
<button class="btn btn-block btn-primary" name="frm_search" id="frm_search">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
</form>
<div id="contacts_list" class="table-responsive"></div>
</div>
<div id="save_contact" class="collapse">
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#save_contact,#search_contact">
<span class="glyphicon glyphicon-circle-arrow-left"></span> Go Back
</button>
</div>
</div>
<form name="frm_contacts" id="frm_contacts" autocomplete="off">
<div class="form-group">
<label class="control-label" for="fname"><span class="label label-primary">First Name:</span></label>
<input type="text" class="form-control" name="frm_first" id="frm_first" placeholder="Enter First Name" maxlength="50" title="A-Z, space, dash, apostrophe, period, comma - no other special characters" pattern="[a-zA-Z][A-Za-z' .,-]{0,49}$" required>
</div>
<div class="form-group">
<label class="control-label" for="lname"><span class="label label-primary">Last Name:</span></label>
<input type="text" class="form-control" name="frm_last" id="frm_last" placeholder="Enter Last Name" maxlength="50" title="A-Z, space, dash, apostrophe, period, comma - no other special characters" pattern="[a-zA-Z][A-Za-z' .,-]{0,49}$" required>
</div>
<div class="form-group">
<label class="control-label" for="email"><span class="label label-primary">Email address:</span></label>
<input type="email" class="form-control" name="frm_email" id="frm_email" placeholder="Enter Email" maxlength="80" required>
</div>
<div class="form-group required">
<label class="control-label" for="phone"><span class="label label-primary">Phone:</span></label>
<input type="tel" class="form-control us-phone" name="frm_phone" id="frm_phone" pattern="\(\d{3}\)[ ]?\d{3}[-]?\d{4}" maxlength="14" title="US based Phone Number in the format of: (xxx) xxx-xxxx" placeholder="(xxx) xxx-xxxx" required>
</div>
<div class="form-group required">
<label class="control-label" for="status"><span class="label label-primary">Status:</span></label>
<select class="form-control" name="frm_status" id="frm_status" required>
<option value="">--Choose--</option>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-11 col-lg-11">
<div id="frm_message" class="alert alert-Submit"></div>
</div>
</div>
</form>
</div>
</div>
<div class="panel-footer">
<p><span>© 2018 MD. All Rights Reserved.</span></p>
</div>
</div>
</div>
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body" id="delete_modalBody"></div>
<div class="modal-footer" id="delete_modalFooter">
<button type="button" class="btn btn-warning confirm_delete" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<script language="javascript" src="App.js"></script>
</body>
</html>
If anyone knows how this can be achieved or some other API's that can be used for this purpose please let me know.
I have a dynamic form for items. First row items form will appear with (+) and (-) button, next they click (+) button and (-) in the previous row and now I have problem when I want to remove row that has (+) and (-), I need to add (+) button on previous row. I read about closest and find, but I cant use it.
here is my html
var index = 1;
$(document).ready(function() {
addItems(index);
});
function addItems(index) {
$('#btn-add-item').remove();
$('#item_list').append(
"<div class='items' id='item_" + index + "'>" +
"<div class='row'>" +
"<div class='col-md-3'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_qty[]' placeholder='Item qty' data-error='Item qty cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-7'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_name[]' placeholder='Item name' data-error='Item name cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-2' id='btn_action'>" +
"<button id='btn-remove-item' type='button' class='btn btn-danger' style='margin-right: 5px' onclick='removeItem(" + index + ")'><i class='fa fa-minus'></i></button>" +
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>" +
"</div>" +
"</div>" +
"</div>"
);
index++;
}
function removeItem(index) {
$('#item_' + index).closest("items").find("#btn_action").append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$('#item_' + index).remove();
index--;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">Tambah Transaksi</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Transaksi</li>
<li class="active">Tambah Transaksi</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="white-box">
<form action="#" class="form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nomor Transaksi</label>
<input type="text" class="form-control" name="transaction_number" id="transaction_number" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nama Pembeli</label>
<input type="text" class="form-control" name="buyer_name" id="buyer_name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Alamat Pembeli</label>
<textarea type="text" class="form-control" name="buyer_address" id="buyer_address" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Items</label>
</div>
</div>
</div>
<div id="item_list"></div>
</form>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="white-box">
</div>
</div>
</div>
Thanks for your help guys.
What you are looking for is .prev and not .closest.
As correctly pointed out by #Priyal Pithadiya, you will need to add a check before you add element.
var $item = $('#item_' + index)
var shouldAppendButton = !!$item.find('#btn-add-item').length;
if (shouldAppendButton)
$item
.prev()
.find("#btn_action")
.append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$item.remove();
Explanation
.closest: It looks in the hierarchy and get to the necessary element. It does not look for previous sibling.
.prev: It looks for previous sibling.
Sample:
var index = 1;
$(document).ready(function() {
addItems(index);
});
function addItems(index) {
$('#btn-add-item').remove();
$('#item_list').append(
"<div class='items' id='item_" + index + "'>" +
"<div class='row'>" +
"<div class='col-md-3'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_qty[]' placeholder='Item qty' data-error='Item qty cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-7'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_name[]' placeholder='Item name' data-error='Item name cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-2' id='btn_action'>" +
"<button id='btn-remove-item' type='button' class='btn btn-danger' style='margin-right: 5px' onclick='removeItem(" + index + ")'><i class='fa fa-minus'></i></button>" +
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>" +
"</div>" +
"</div>" +
"</div>"
);
index++;
}
function removeItem(index) {
var $item = $('#item_' + index)
var shouldAppendButton = !!$item.find('#btn-add-item').length;
if(shouldAppendButton)
$item
.prev()
.find("#btn_action")
.append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$item.remove();
index--;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">Tambah Transaksi</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Transaksi</li>
<li class="active">Tambah Transaksi</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="white-box">
<form action="#" class="form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nomor Transaksi</label>
<input type="text" class="form-control" name="transaction_number" id="transaction_number" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nama Pembeli</label>
<input type="text" class="form-control" name="buyer_name" id="buyer_name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Alamat Pembeli</label>
<textarea type="text" class="form-control" name="buyer_address" id="buyer_address" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Items</label>
</div>
</div>
</div>
<div id="item_list"></div>
</form>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="white-box">
</div>
</div>
</div>
Pointers:
IDs must be unique. Having same id in all items div is wrong.
You can also add a delegate instead of adding handlers in every item's markup
I am designing a application in PHP and using javascript to perform add/edit/delete .The data is getting inserted correctly but when i click on edit button the data dispalyed is in the centre if input box. i tried using CSS but nothing happened. I am also not able to type in either to correct the mistake.Below is code
PHP:
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<?php include_once("header.php"); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" integrity="sha256-p6xU9YulB7E2Ic62/PX+h59ayb3PBJ0WFTEQxq0EjHw=" crossorigin="anonymous" />
</head>
<!-- END HEAD -->
<body class="page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-content-white">
<div class="page-wrapper">
<?php include_once("navbar.php"); ?>
<!-- BEGIN HEADER & CONTENT DIVIDER -->
<div class="clearfix">
</div>
<!-- END HEADER & CONTENT DIVIDER -->
<!-- BEGIN CONTAINER -->
<div class="page-container">
<?php include_once("side_bar.php"); ?>
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<button class="btn btn-success mt-sweetalert hide" data-title="Sweet Alerts with Icons" data-message="Success Icon" data-type="success" data-allow-outside-click="true" data-confirm-button-class="btn-success" id="msgbox" >Icon Success Alert</button>
<button class="btn btn-warning mt-sweetalert hide" data-title="Sweet Alerts with Icons" data-message="Warning Icon" data-type="warning" data-allow-outside-click="true" data-confirm-button-class="btn-warning" id="wmsg">Icon Warning Alert</button>
<a class="btn green btn-outline sbold" data-toggle="modal" href="#draggable"> + Add Assessment Type </a>
<div class="table-responsive">
<table id="users" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="display:none;">ID</th>
<th onclick="sortTable(1)">Assessment type code</th>
<th onclick="sortTable(2)">Assessment Name</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody id="table_body">
<tr>
<th style="display:none;">ID</th>
<th>
<input type="text" class="form-control" id="codes" onkeyup="myFunction(this.id, 1)" placeholder="Search for codes.." title="Type in a name">
</th>
<th>
<input type="text" class="form-control" id="names" onkeyup="myFunction(this.id, 2)" placeholder="Search for names.." title="Type in a name">
</th>
<th colspan="2"></th>
</tr>
<?php
include_once PHP_PATH .'/config.php';
$sql = "select * from list_assessment_types";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$aid = $row["pk_assess_type_id"];
$code = $row["assess_type_code"];
$name = $row["assess_type_name"];
?>
<tr id="<?php echo $aid ?>">
<td style="display:none;"></td>
<td>
<?php echo $code ?>
</td>
<td>
<?php echo $name ?>
</td>
<td><a name="edit" class="btn blue btn-outline sbold" data-toggle="modal" href="#draggable1"><i class="fa fa-pencil-square-o fa-1x" aria-hidden="true"></i> Edit</a>
</td>
<td><button name="del" class="btn red btn-outline sbold"><i class="fa fa-trash fa-1x" aria-hidden="true"></i> Delete</button>
</td>
</tr>
<?php
}
db_close();
?>
</tbody>
</table>
</div>
<!-- Modal to add assessment type-->
<div class="modal fade draggable-modal" id="draggable" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Add new Assessment Type</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="code">Assessment type code</label>
<input type="text" name="code" maxlength="15" id="code" value="" class="form-control" />
</div>
<div class="form-group">
<label for="name">Assessment name</label>
<input type="text" name="name" id="name" maxlength="20" value="" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button id="new_save" type="button" class="btn green" data-dismiss="modal">Save changes</button>
<button type="button" class="btn dark btn-outline" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- Modal finishes here-->
<!-- Modal to edit assessment type-->
<div class="modal fade draggable-modal" id="draggable1" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Edit Assessment Type</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="e_code">Assessment type code</label>
<input type="text" name="e_code" maxlength="15" id="e_code" value="" placeholder="test" class="form-control" />
</div>
<div class="form-group">
<label for="e_name">Assessment name</label>
<input type="text" name="e_name" id="e_name" maxlength="20" value="" placeholder="test" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button id="e_save" type="button" class="btn green" data-dismiss="modal">Save changes</button>
<button type="button" class="btn dark btn-outline" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- Modal finishes here-->
</div>
<!-- END QUICK SIDEBAR -->
</div>
</div>
<!-- END CONTAINER -->
<?php include_once("footer_text.php"); ?>
</div>
<div class="quick-nav-overlay"></div>
<?php include_once("footer.php"); ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script type="text/javascript" src="<?= ASSET_PATH ?>assets/staff_js/assessment_type.js"></script>
<script>
function myFunction(tab, s) {
var input, filter, table, tr, td, i;
input = document.getElementById(tab);
filter = input.value.toUpperCase();
table = document.getElementById("users");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[s];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<script>
$("#draggable").draggable({
handle: ".modal-header"
});
</script>
</body>
</html>
JS
var x, okay_content, idx;
$(function () {
var parentId, tr;
$('#new_save').click(function () {
var code = $('#code').val();
var name = $('#name').val();
$.ajax({
url: 'class_codes.php',
type: 'post',
dataType: 'json',
data: {
from: 'insert',
code: code,
name: name
},
success: function (response) {
// Check if data is redundant.
if (response[0] === "REDUNDANT") {
alert("Data already exist.");
} else if (response[0] === "EMPTY") {
alert("Field can't be left empty");
} else if (response[0] == "1")
{
// Insert or Edit
$("#users tbody").append("<tr id=" + response[1] + "><td style='display:none;'><td>" + code + "</td>" + "<td>" + name + "</td>" + "<td><a name= 'edit' href='' class='btn blue btn-outline sbold'><i class='fa fa-pencil-square-o fa-1x' aria-hidden='true'></i> Edit</a></td><td><button name='del' class='btn red btn-outline sbold'><i class='fa fa-trash fa-1x' aria-hidden='true'></i> Delete</button></td></tr>");
//sortTable(1);
alert("Class Code created successfully.");
return false;
} else {
alert("Error: " + response[0]);
}
},
error: function (error) {
okay_content = error[0];
$("#okay").dialog("open");
}
});
});
$(document).on('click', 'a[name="edit"]', function () {
tr = $(this).parents('tr');
$('#e_code').val(tr.find("td:eq(1)").text());
$('#e_name').val(tr.find("td:eq(2)").text());
parentId = tr.attr('id');
});
$(document).on('click', '#e_save', function () {
var code = $('#e_code').val();
var name = $('#e_name').val();
alert("CODE: " + code + " NAME: " + name + " ID: " + parentId);
$.ajax({
url: 'assessment_type.php',
type: 'post',
dataType: 'json',
data: {
from: 'edit',
id: parentId,
code: code,
name: name
},
success: function (response) {
// Check if data is redundant.
if (response[0] === "REDUNDANT") {
alert("Data already exist.");
} else if (response[0] === "EMPTY") {
alert("Field can't be left empty");
// Check if field is empty
// okay_content = "Field can't be left empty ";
} else if (response[0] == "1")
{
// Insert or Edit
tr.remove();
$("#users tbody").append("<tr>" + "<td style='display:none;'>" + response[1] + "<td>" + code + "</td>" + "<td>" + name + "</td>" + "<td><a href='' class='btn blue btn-outline sbold'><i class='fa fa-pencil-square-o fa-1x' aria-hidden='true'></i> Edit</a></td>" + "<td><button name='del' class='btn red btn-outline sbold'><i class='fa fa-trash fa-1x' aria-hidden='true'></i> Delete</button></td></tr>");
//sortTable(1);
alert("Class Code edited successfully.");
return false;
} else {
alert("Error: " + response[0]);
}
},
error: function (error) {
okay_content = error[0];
$("#okay").dialog("open");
}
});
});
$(document).on('click', 'button[name="del"]', function () {
var row = $(this).parents('tr');
var id = row.attr('id');
$.ajax({
url: 'class_codes.php',
type: 'post',
dataType: 'json',
data: {
id: id,
from: 'delete'
},
success: function (suc) {
if (suc[0] == "1") {
alert("Class Code deleted successfully.");
$(this).addClass('btn-success ')
row.fadeOut(1000);
}
},
error: function (error) {
alert(error);
}
});
});
});
I am not sure where I am going wrong. Looks like the issue is within JS as I havbe tried turning entore CSS off but the issue still persists. Help please !!!
the php eho statement should be in 1 line