How to add delete button to a column using JS? - javascript

I have experience with PHP and HTML, but I am unfamiliar with JS. I have all the code needed, but I can't put it together. I have a table and need to add a delete button that will remove the file on that row. As shown in the picture below, but without the edit button:
When click on the Search button, the table is displayed (here is where I need the delete button):
index.php
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;'/>
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px; display:none">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>
main.js
function Search(){
var crop = $("#crop").val();
var type = $("#type").val();
var year = $("#year").val();
var season = $("#season").val();
var location = $("#location").val();
var subLocation = $("#sublocation").val();
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
$.ajax({
url: "Resources/PHP/Search.php",
dataType: 'text',
data: {
crop: crop,
type: type,
year: year,
location: location,
season: season,
sublocation: subLocation
},
success: function(response) {
var data = JSON.parse(response);
var items = "";
var firstSet = 0;
if (data.length > 0)
{
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
$("#imported-set-wrapper").html(table);
$.each(data,function(index,item)
{
if (index == 0){
firstSet = item.ID;
}
items+= "<tr id='data-set-" + item.ID + "' onclick='SelectDataSet(\"" + item.ID + "\"); return false;' style='cursor:pointer'>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
var rowHeight = 61;
var padding = 10;
var actualHeight = (data.length + 1) * rowHeight + padding;
var maxHeight = 300;
var height = actualHeight < maxHeight ? actualHeight : maxHeight;
$('#imported-set-table').fxdHdrCol({
fixedCols: 0,
width: 1100,
height: height,
colModal: [
//added
{ width: 150, align: 'center' },
//added
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 150, align: 'center' },
{ width: 250, align: 'center' },
{ width: 175, align: 'center' },
{ width: 150, align: 'center' },
],
sort: false
});
if (firstSet > 0){
$("#next").prop("disabled", false);
SelectDataSet(firstSet);
$("#data-set-fs").show();
} else {
alert("No dataset found");
}
}
$("#processing").hide();
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
$("#processing").hide();
}
});
}
Useful code from picture 1
"<input id='delete-" + type + "-" + item.ID +"' type='image' class='image-button delete-button' src='Resources/Images/delete.png' alt='Delete' onclick='Delete(" + item.ID +", \"" + type + "\"); return false;' title='Delete'>" +
"<input id='confirmDelete-" + type + "-" + item.ID +"' type='image' class='image-button confirm-delete-button' src='Resources/Images/confirm.png' alt='Confirm' style='display:none' onclick='ConfirmDelete(" + item.ID +", \"" + type + "\"); return false;' title='Confirm'>" +
"<input id='cancelDelete-" + type + "-" + item.ID +"' type='image' class='image-button cancel-delete-button' src='Resources/Images/cancel.png' alt='Cancel' style='display:none' onclick='CancelDelete(" + item.ID +", \"" + type + "\"); return false;' title='Cancel'>" +
function Delete(id, type){
$('#confirmDelete-' + type + '-' + id).show();
$('#cancelDelete-' + type + '-' + id).show();
$('#delete-' + type + '-' + id).hide();
CancelEdit(id);
}
function CancelDelete(id, type){
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
}
function ConfirmDelete(id, type){
$.ajax({
url: 'Resources/PHP/' + type + '.php',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {
$('#confirmDelete-' + type + '-' + id).hide();
$('#cancelDelete-' + type + '-' + id).hide();
$('#delete-' + type + '-' + id).show();
alert("The " + type + " has been deleted.");
GetList(type);
} else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});
}
Additional info: "//added" are additional lines trying to achieve mentioned goal.

You can add your button like this "<button data-id = " + item.ID + " class='delete'>Delete</button>" where data-id has your item.ID value this will get passed to your backend to perform delete operation.
Then , when delete button get clicked this $(document).on("click", ".delete",.. will get called you can show confirm-box so if user click ok then call your ajax to delete that trs data using selector.closest('tr').remove() where selector refer to the button which has been clicked .
Demo Code :
//dummy datas
var data = [{
"Year": "2016",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "1"
}, {
"Year": "2017",
"Season": "somehting",
"Crop": "12",
"Type": "A",
"Location": "India",
"SubLocation": "Sub",
"ID": "2"
}]
function Search() {
//some codes..
$("#imported-set-wrapper").html("");
$("#imported-list-wrapper").html("");
$("#processing").show();
//other codes...
var table = "<table id='imported-set-table'>" +
"<thead>" +
"<tr>" +
//added
"<th>Delete</th>" +
//added
"<th>Year</th>" +
"<th>Season</th>" +
"<th>Crop</th>" +
"<th>Type</th>" +
"<th>Location</th>" +
"<th>Sub-location</th>" +
"</tr>" +
"</thead>" +
"<tbody id='imported-set'>" +
"</tbody>" +
"</table>";
var items = "";
$("#imported-set-wrapper").html(table);
$.each(data, function(index, item) {
if (index == 0) {
firstSet = item.ID;
}
items += "<tr id='data-set-" + item.ID + "' onclick='' style='cursor:pointer'>" +
"<td style='overflow:hidden'>" +
//added button with data-* attribute
"<button data-id = " + item.ID + " class='delete'>Delete</button>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Season + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Crop + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Type + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.Location + "</span>" +
"</td>" +
"<td style='overflow:hidden'>" +
"<span>" + item.SubLocation + "</span>" +
"</td>" +
"</tr>";
});
$("#imported-set").html(items);
//soem ot//other codes..
}
//onclick of delete button
$(document).on("click", ".delete", function() {
var id = $(this).data('id'); //get id
var selector = $(this);
console.log(id)
//show confirm box if yes
if (confirm("Are you sure?")) {
//ajax call
/*$.ajax({
url: 'url',
dataType: 'text',
data: { id: id, action: 'delete'},
success: function(response) {
if (response == "1") {*/
selector.closest('tr').remove() //remove tr
/* } else {
alert("Could not delete the " + type + ". Error: " + response + ".");
}
}
});*/
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="clear:both; margin-bottom: 10px"></div>
<input type='button' class='button right-button' value='Search' onclick='Search(); return false;' />
<div style="clear:both; margin-bottom: 10px"></div>
<fieldset id="data-set-fs" style="width:93%; padding-top: 10px;">
<legend>Data Set</legend>
<div id="imported-set-wrapper"></div>
</fieldset>

Where you have:
//added
"<td style='overflow:hidden'>" +
"<span>" + item.Year + "</span>" +
"</td>" +
//added
Doesn't this need to be the button? E.g.
<td><button onclick='deleteFunction(item.id)'>Delete</button></td>

Related

Unable To See Calculated Field in LocalStorage using JavaScript

I have the following JS code for which I am calculating the insurance cost based on input provided by the user:
function AddQuote() {
if (ValidateInputs()) {
var json = {};
$(":input").each(function () {
json[$(this).attr("id")] = $(this).val();
});
var nextId = Number(localStorage.getItem('nextId'));
if (!nextId) {
nextId = 1;
}
localStorage.setItem("quote-" + nextId, JSON.stringify(json));
localStorage.setItem("nextId", String(nextId + 1));
$(location).prop('href', 'viewQuote.html?' + nextId);
}
}
function LoadQuoteData(id) {
var json = JSON.parse(localStorage.getItem("quote-" + id));
$(":input").each(function () {
$(this).val(json[$(this).attr("id")]);
});
var driverAge = Number(json['age']);
var driverExperience = Number(json['experience']);
var driverAccidents = Number(json['accidents']);
var subQuote;
var insuranceQuote = Number(json['finalQuote']);
if (driverExperience === 0) {
subQuote = 4000;
}
else if (driverExperience >= 1 && driverExperience <= 9) {
subQuote = 2500;
}
else {
subQuote = 1800;
}
if (driverAge >= 30 && driverExperience >= 2) {
insuranceQuote = subQuote * 0.75;
}
else {
insuranceQuote = subQuote;
}
//console.log(insuranceQuote);
console.log(json);
$("#finalQuote").val("$" + insuranceQuote);
}
I am using this in my HTML code as follows:
<script>
$(document).ready(function () {
var localStorageItems = Object.entries(localStorage);
var htmlCode = "";
$(localStorageItems).each(function () {
if ($(this)[0].startsWith("quote")) {
console.log($(this)[0]);
console.log($(this)[1]);
var quoteData = JSON.parse($(this)[1]);
var quoteAmount = "$" + quoteData['finalQuote'];
htmlCode +=
"<div class='container'>" +
"<div class='row pb-4 pt-4' style='border-bottom: 1px solid rgba(0,0,0,.125);'>" +
"<div class='col-md-6 '>" +
"<div class='card-header' style='margin-left: -1rem; margin-right: -1rem;'>Customer Information</div>" +
"<span class='d-block'><strong>First Name:</strong> " + quoteData['firstName'] + "</span>" +
"<span class='d-block'><strong>Last Name:</strong> " + quoteData['lastName'] + "</span>" +
"<span class='d-block'><strong>Address:</strong> " + quoteData['address'] + "</span>" +
"<span class='d-block'><strong>City:</strong> " + quoteData['city'] + "</span>" +
"<span class='d-block'><strong>Province:</strong> " + quoteData['province'] + "</span>" +
"<span class='d-block'><strong>Postal Code:</strong> " + quoteData['postalCode'] + "</span>" +
"<span class='d-block'><strong>Phone Number:</strong> " + quoteData['phone'] + "</span>" +
"<span class='d-block'><strong>Email:</strong> " + quoteData['email'] + "</span>" +
"</div>" +
"<div class='col-md-6'>" +
"<div class='card-header' style='margin-left: -1rem; margin-right: -1rem;'>Driving Information</div>" +
"<span class='d-block'><strong>Accidents:</strong> " + quoteData['accidents'] + "</span>" +
"<span class='d-block'><strong>Age:</strong> " + quoteData['age'] + "</span>" +
"<span class='d-block'><strong>Driving Experience:</strong> " + quoteData['experience'] + "</span>" +
"<span class='d-block'><strong>Insurance Quote:</strong> " + quoteAmount + "</span>" +
"<span class='d-block'><strong>" +
"</span>" +
"</div>" +
"</div>" +
"</div>" +
"</div>";
};
});
$("#quotesList").html(htmlCode);
});
</script>
But the problem is that the calculated finalQuote is not showing up on this HTML page (but all other fields are). Any ideas on what I'm missing / not doing correctly?

How order table after selected option

I have URL API and i did group by "date".
But I would like to know how I can after I selected option from the data Importance its will order only the rows (and keep the date) by Importance.
Image how its order now:
http://prntscr.com/ebgodq
My code:
var table = $(".top-table");
var body = table.children("tbody");
var regdate = /^(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})$/;
$.get("http://api.tradingeconomics.com/calendar?c=guest:guest", function (data) {
showData(data);
});
function showData (data) {
//---Sort the data from the server
data.sort(function (a, b) {
return (new Date(a.Date)) - (new Date(b.Date));
});
var group = data.reduce(function (before, current) {
var day = current.Date.replace(regdate, "$1");
var hour = current.Date.replace(regdate, "$2");
if (!before[day]) {
before[day] = [];
}
current.Hour = hour;
before[day].push(current);
return before;
}, {});
for(var date in group) {
body.append("<tr style='text-align: left;background: #fafafa;line-height: 35px;border-bottom: 2px solid #ff9d00;font-size: 13pt;font-weight: normal;'>" +
"<th width='50%'>" + date + "</th>" +
"<th width='12%'>Actual</th>" +
"<th width='12%'>Previous</th>" +
"<th width='12%'>Forecast</th>" +
"<th width='4%'></th></tr>");
group[date].forEach(function(row){
var rowA = parseInt(row.Actual) > 0 ?
"<span style='color:red;'>" + noCommas(row.Actual) + "</span>" :
"<span style='color:green;'>" + noCommas(row.Actual) + "</span>";
var rowB = parseInt(row.Previous) > 0 ?
"<span style='color:red;'>" + noCommas(row.Previous) + "</span>" :
"<span style='color:green;'>" + noCommas(row.Previous) + "</span>";
var rowC = parseInt(row.Forecast) > 0 ?
"<span style='color:red;'>" + noCommas(row.Forecast) + "</span>" :
"<span style='color:green;'>" + noCommas(row.Forecast) + "</span>";
var Time = hourwithAMPM(row.Date);
body.append("<tr style='border-bottom: 1px solid #eeeeee;text-align: left;font-size: 12pt;font-weight: 300;line-height: 30px;'>" +
"<td><span class='im-" + row.Importance + "'>" + Time + "</span>" +
"<span style='margin: 0 10px 0;'><img src='/images/calendar/flags/" + noCommas(row.Country) + ".png' width='16' height='16' /></span>" +
"<span style='font-size: 11pt;color:#999999;font-weight: 600;word-spacing: -1px;margin: 0 5px 0;'>" + noCommas(row.Event) + "</span>"+
"<span style='color:#333333;'> " + noCommas(row.Reference) + "</span>" +
"</td>" +
"<td>" + rowA + "</td>" +
"<td>" + rowB + "</td>" +
"<td>" + rowC + "</td>" +
"<td><div class='arrow-down'></div></td>" +
"</tr>");
body.append("<tr class='showRow' style='display:none;'><td>yay!!!</td></tr>");
});
}
}

Asp.net Same button to edit and Save using Jquery

I have something like that,
When I click on edit, It populate the record of that student back to Text Boxes. I want to use the same 'Save' button to save and edit. I am also saving the student through same button.
I want that when someone click the edit button Save ajax call would not call. I am stuck on that. Currently when i edit the record, same record also inserted. If anyone want to see the code I can edit the question for that .
Thanks
function UpdateStudent(id, name, fname, roll, age, phone, address) {
debugger
$(document).ready(function () {
$("#students").show();
$("#txtName").val(name);
$("#txtFatherName").val(fname);
$("#txtRollNo").val(roll);
$("#txtAge").val(age);
$("#txtPhone").val(phone);
$("#txtAddress").val(address);
if (id) {
$("#btnSave").click(function (e) {
e.preventDefault();
debugger
var Name = $("#txtName").val();
var FatherName = $("#txtFatherName").val();
var RollNo = $("#txtRollNo").val();
var Age = $("#txtAge").val();
var Phone = $("#txtPhone").val();
var Address = $("#txtAddress").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "StudentManagement.aspx/UpdateStudent",
data: "{'ID': '" + id + "','Name':'" + Name + "','FatherName':'" + FatherName + "','RollNo':'" + RollNo + "','Age':'" + Age + "','Phone':'" + Phone + "','Address':'" + Address + "'}",
dataType: "json",
success: function (data) {
debugger
$("#txtName").val("");
$("#txtFatherName").val("");
$("#txtRollNo").val("");
$("#txtAge").val("");
$("#txtPhone").val("");
$("#txtAddress").val("");
$("#students").hide();
var array = data.d;
$("#table").find("tr:gt(0)").remove();
for (var i = 0; i < array.length - 1; i++) {
var row = "<tr>"
+ "<td>" + array[i].ID + "</td>"
+ "<td>" + array[i].Name + "</td>"
+ "<td>" + array[i].FatherName + "</td>"
+ "<td>" + array[i].RollNo + "</td>"
+ "<td>" + array[i].Age + "</td>"
+ "<td>" + array[i].Phone + "</td>"
+ "<td>" + array[i].Address + "</td>"
+ "<td><a href='#' onclick='UpdateStudent(\"" + array[i].ID + "\",\"" + array[i].Name + "\",\"" + array[i].FatherName + "\",\"" + array[i].RollNo + "\",\"" + array[i].Age + "\",\"" + array[i].Phone + "\",\"" + array[i].Address + "\")'>Edit</a></td>"
+ "<td><a href='#' onclick='DeleteStudent( " + array[i].ID + " )'>Delete</a></td>"
+ "</tr>"
$("#table").append(row);
}
},
error: function (response) {
debugger
alert(response);
}
});
return false;
});
}
})
}
And Insert Student code it below, also
function InsetStudent() {
debugger
$(document).ready(function () {
var Name = $("#txtName").val();
var FatherName = $("#txtFatherName").val();
var RollNo = $("#txtRollNo").val();
var Age = $("#txtAge").val();
var Phone = $("#txtPhone").val();
var Address = $("#txtAddress").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "StudentManagement.aspx/CreateStudent",
data: "{'Name':'" + Name + "','FatherName':'" + FatherName + "','RollNo':'" + RollNo + "','Age':'" + Age + "','Phone':'" + Phone + "','Address':'" + Address + "'}",
dataType: "json",
success: function (data) {
debugger
$("#txtName").val("");
$("#txtFatherName").val("");
$("#txtRollNo").val("");
$("#txtAge").val("");
$("#txtPhone").val("");
$("#txtAddress").val("");
$("#students").hide();
var array = data.d;
$("#table").find("tr:gt(0)").remove();
for (var i = 0; i < array.length; i++) {
var row = "<tr>"
+ "<td>" + array[i].ID + "</td>"
+ "<td>" + array[i].Name + "</td>"
+ "<td>" + array[i].FatherName + "</td>"
+ "<td>" + array[i].RollNo + "</td>"
+ "<td>" + array[i].Age + "</td>"
+ "<td>" + array[i].Phone + "</td>"
+ "<td>" + array[i].Address + "</td>"
+ "<td><a href='#' onclick='UpdateStudent(\"" + array[i].ID + "\",\"" + array[i].Name + "\",\"" + array[i].FatherName + "\",\"" + array[i].RollNo + "\",\"" + array[i].Age + "\",\"" + array[i].Phone + "\",\"" + array[i].Address + "\")'>Edit</a></td>"
+ "<td><a href='#' onclick='DeleteStudent( " + array[i].ID + " )'>Delete</a></td>"
+ "</tr>"
$("#table").append(row);
}
},
error: function (response) {
debugger
alert(response);
}
});
return false;
})
}
And insertStudent call on jquery load, like
$("#btnSave").click(function (e) {
e.preventDefault();
InsetStudent();
})
You can do this like:
STEP1:
If you have any required field in your form then use this
$("#btnSave").click(function (e) {
e.preventDefault();
if(Check value of required field not null or empty)
{
UpdateStudent(id, name, fname, roll, age, phone, address);
}
else
{
InsetStudent();
}
});
STEP2:
If you are not using any required field in your form then use hidden field. default value of this Hidden field will be false. When user will click on edit first assign true to hidden field.
$("#btnSave").click(function (e) {
e.preventDefault();
if(Check value of Hidden field true)
{
UpdateStudent(id, name, fname, roll, age, phone, address);
//Here update hidden field value to false after completing the operation
}
else
{
InsetStudent();
}
});
hope this logic will help you.
Remove only btnSave click event
$("#btnSave").click(function (e) {
});
from your function UpdateStudent and call the
function UpdateStudent directly on edit button click event

AngularJS: function not defined error when html is generated from Javascript

I amd dynamically generating my edit table from javaScript. But function mentioned via it are not recognaizeable from AngularJS, for that, I am not able to remove and edit my rows.
Here HvacStandards() and checkemail() and showInvite() are only working. for other's i am getting following exception in chorom console:
Errors:
Uncaught ReferenceError: editRow is not defined
Uncaught ReferenceError: deleteRow is not defined
AngularJs code
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button onclick='editRow(" + rowID
+ ")'>Edit</button> " + "<button onclick='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
$("#inviteTable").append(sHtml);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};
$scope.editRow = function(rowID) {
$('#teamName').val($('#tName' + rowID).html());
$('#email').val($('#mail' + rowID).html());
$scope.currentRow = rowID;
};
$scope.saveEdits = function (){
$('#teamName' + currentRow).html($('#tName').val());
$('#email' + currentRow).html($('#mail').val());
$("#teamName,#email").val("");
$scope.currentRow = -1;
};
$scope.deleteRow = function (rowID) {
$('#row' + rowID).remove();
};
$scope.showInvite = function(){
$scope.show = true;
$scope.formData = {};
};
and my html is like following:
<div name="showInviteDiv" id="showInviteDiv">
<a ng-click="showInvite()" ng-show="!show">Invite a Team</a>
</div>
<div class="invite-form" name="inviteTeamDiv" id="inviteTeamDiv" ng-show="show">
<form ng-submit="HvacStandards()" novalidate class="css-form"
name='inviteTeamsForm'>
<div>
<input type="text" name="teamName" ng-model="formData.teamName" id="teamName"
placeholder="Team Name" style="width: 38%;" required="required"
ng-minlength="6" ng-maxlength="30">
<input
type="text" name="email" ng-model="formData.email" id="email"
placeholder="Email" style="width: 38%;" required="required"
ng-pattern="/^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/" ng-change="checkEmail(form Data.email)" ng-blur="checkEmail(formData.email)">
</div>
<div>
<input type="submit" value="Invite Team"
ng-disabled="inviteTeamsForm.$invalid || isEmailExists"> or <a ng-click="hideInvite()">I'm done sending invites</a>
</div>
In the Table that you are creating, you used onclick instead of ng-click. You need to use ng-click in order to use scope function.
So your HvacStandards function will look like this:
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button ng-click='editRow(" + rowID
+ ")'>Edit</button> " + "<button ng-click='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
$("#inviteTable").append(sHtml);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button ng-click='editRow(" + rowID
+ ")'>Edit</button> " + "<button ng-click='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
//$("#inviteTable").append(sHtml); // don't do this
// use compile in following manner
$("#inviteTable").append(
$compile(sHtml)($scope)
);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};
try this
$scope.HvacStandards = function () {
var rowID = $scope.newRow;
if ($scope.currentRow > 0) {
saveEdits();
} else {
var teamName = $("#teamName").val();
var email = $("#email").val();
var sHtml = "<tr id='row"+rowID+"'>"
+ "<td id=\"tno" + rowID + "\">" + rowID
+ "</td>"
+ "<td id=\"tName" + rowID + "\">" + teamName
+ "</td>" + "<td id=\"mail" + rowID + "\">" + email
+ "</td>" + "<td><button ng-click='editRow(" + rowID
+ ")'>Edit</button> " + "<button ng-click='deleteRow("
+ rowID + ")'>Delete</button>" + "</tr>";
// $compile(sHtml)($scope) aissign to variable:
let shown = $compile(sHtml)($scope);
$("#inviteTable").append(
shown;
);
$scope.newRow++;
$("#teamName,#email").val("");
$scope.emails[$scope.number]=$scope.formData.email;
}
};

JSON TypeError: Cannot read property 'image' of undefined

i already make this JSON. but i found this error
a +="<div class=\"back\">"
+ "<img src=\"[[--ImgRootDir--]]resource/image/button_back.png\" width=\"85px\" />"
+ "</div>"
+ "<div class=\"bg\">"
+ "<img src=\"[[--ImgRootDir--]]resource/image/Film_Level.png\" width=\"590px\" height=\"600px\" />"
+ "</div>"
+ "<div class=\"lvle\">"
+ "<table width=\"84%\">"
+ "<tr>"
+ getSubsHTML(nodes[0].image, jsonStage.indexOf("2014_2012.json_0_0"),0)
+ getSubsHTML(nodes[1].image, jsonStage.indexOf("2014_2012.json_0_1"),1)
+ getSubsHTML(nodes[2].image, jsonStage.indexOf("2014_2012.json_0_2"),2)
+ getSubsHTML(nodes[3].image, jsonStage.indexOf("2014_2012.json_0_3"),3)
+ getSubsHTML(nodes[4].image, jsonStage.indexOf("2014_2012.json_0_4"),4)
+ "</tr>"
+ "<tr>"
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_0"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_1"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_2"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_3"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_4"))
+ "</tr>"
+ "<tr>"
+ getSubsHTML(nodes[5].image, jsonStage.indexOf("2014_2012.json_0_5"),5)
+ getSubsHTML(nodes[6].image, jsonStage.indexOf("2014_2012.json_0_6"),6)
+ getSubsHTML(nodes[7].image, jsonStage.indexOf("2014_2012.json_0_7"),7)
+ getSubsHTML(nodes[8].image, jsonStage.indexOf("2014_2012.json_0_8"),8)
+ getSubsHTML(nodes[9].image, jsonStage.indexOf("2014_2012.json_0_9"),9)
+ "</tr>"
+ "<tr>"
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_5"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_6"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_7"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_8"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_9"))
+ "</tr>"
+ "<tr>"
+ getSubsHTML(nodes[10].image, jsonStage.indexOf("2014_2012.json_0_10"),10)
+ getSubsHTML(nodes[11].image, jsonStage.indexOf("2014_2012.json_0_11"),11)
+ getSubsHTML(nodes[12].image, jsonStage.indexOf("2014_2012.json_0_12"),12)
+ getSubsHTML(nodes[13].image, jsonStage.indexOf("2014_2012.json_0_13"),13)
+ getSubsHTML(nodes[14].image, jsonStage.indexOf("2014_2012.json_0_14"),14)
+ "</tr>"
+ "<tr>"
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_10"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_11"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_12"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_13"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_14"))
+ "</tr>"
+ getSubsHTML(nodes[15].image, jsonStage.indexOf("2014_2012.json_0_15"),15)
+ getSubsHTML(nodes[16].image, jsonStage.indexOf("2014_2012.json_0_16"),16)
+ getSubsHTML(nodes[17].image, jsonStage.indexOf("2014_2012.json_0_17"),17)
+ getSubsHTML(nodes[18].image, jsonStage.indexOf("2014_2012.json_0_18"),18)
+ getSubsHTML(nodes[19].image, jsonStage.indexOf("2014_2012.json_0_19"),19)
+ "</tr>"
+ "<tr>"
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_15"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_16"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_17"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_18"))
+ getStageHTML(jsonStage.indexOf("2014_2012.json_0_19"))
+ "</tr>"
+ "</table>"
+ "</div>"
+ "<div class=\"left\">"
+ "<img src=\"[[--ImgRootDir--]]resource/image/Camera_kiri.png\" width=\"150px\" />"
+ "</div>"
+ "<div class=\"right\">"
+ "<img src=\"[[--ImgRootDir--]]resource/image/Camera_kanan.png\" width=\"150px\" />"
+ "</div>";
and this is the json
nodes: [
{
id: "2014_2012.json_0_0",
image: "_1396278834_af_org.png",
question: "1. What is this ?",
answer: "EXX",
hint: "asdadsadsadasdasdaads"
},
{
id: "2014_2012.json_0_0",
image: "_1396278834_af_org.png",
question: "1. What is this ?",
answer: "EXX",
hint: "asdadsadsadasdasdaads"
},
Ok, made some assumptions but this worked: http://jsfiddle.net/sp1nf731/3/
Are you referencing your json variable correctly?
var x = { nodes: [
{
id: "2014_2012.json_0_0",
image: "_1396278834_af_org.png",
question: "1. What is this ?",
answer: "EXX",
hint: "asdadsadsadasdasdaads"
},
{
id: "2014_2012.json_0_0",
image: "_1396278834_af_org.png",
question: "1. What is this ?",
answer: "EXX",
hint: "asdadsadsadasdasdaads"
}
] };
console.log( x.nodes[1].image );
This works fine for me
I do not know how you get nodes, but if inline you need
var nodes=[
{ .... },
{ .... },
{ .... }
]; // no comma on the last
Here is a suggestion to shorten your code in jQuery
$(function() {
var $rowa=$("<tr/>"), $rowb=$("<tr/>"),
$.each(nodes,function(i,node) {
if (i>0 && i%5==0) {
$("#table1 tbody").append($rowa).append($rowb);
}
$rowa.append(getSubsHTML(node.image, jsonStage.indexOf("2014_2012.json_0_"+i),i);
$rowb.append(getStageHTML(jsonStage.indexOf("2014_2012.json_0_"+i));
});
// here you may test if i%5 !=0 and add the last rows
});

Categories