Im using a jqueryAjax function in a jsp page to display a html table. The function returns response as a json object. Im using the json object, iterating the same and displaying the column values. But if the field value is empty, then the corresponding value in the html table is specified as 'undefined' Below is my sample code
$.each(data1, function (i, item) {
trHTML += '<tr><td >' + item.appnName + '</td><td>' + item.Defectsin2014 + '</td><td>' + item.Defectsin2015 + '</td><td>'+
item.DefectsasperBenchmarks +'</td><td>'+item.costDefect + '</td><td>'+ item.req2014 + '</td><td>'+ item.req2015 +'</td><td>' +
item.ba+ '</td><td>'+ item.config+'</td><td>'+ item.Financials+ '</td><td>' + item.bReports + '</td><td>'+
item.qa + '</td></tr>';
});
$('#records_table').append(trHTML);
In the above, if a particular field is not available in the json for example, if item.req2015 data is not available for a particular row, then the html table displays the corresponding field as 'undefined'.I want the application to display an empty or blank field if the data is not available. Is there any way to acheive the same.
Any help on this is much appreciated.
Check the properties and give them an default before using them.
$.each(data1, function (i, item) {
item.appnName = item.appnName || " ";
item.Defectsin2014 = item.Defectsin2014 || " ";
item.Defectsin2015 = item.Defectsin2015 || " ";
item.costDefect = item.costDefect || " ";
item.req2014 = item.req2014 || " ";
item.req2015 = item.req2015 || " ";
item.ba = item.ba || " ";
item.config = item.config || " ";
item.Financials = item.Financials || " ";
item.bReports = item.bReports || " ";
item.qa = item.qa || " ";
trHTML += '<tr><td >' + item.appnName + '</td><td>' + item.Defectsin2014 + '</td><td>' + item.Defectsin2015 + '</td><td>'+
item.DefectsasperBenchmarks +'</td><td>'+item.costDefect + '</td><td>'+ item.req2014 + '</td><td>'+ item.req2015 +'</td><td>' +
item.ba+ '</td><td>'+ item.config+'</td><td>'+ item.Financials+ '</td><td>' + item.bReports + '</td><td>'+
item.qa + '</td></tr>';
});
$('#records_table').append(trHTML);
Or even shorter possible with an inline decision:
trHTML += '<tr><td >' + (item.appnName || " ") + '</td><td>' + (item.Defectsin2014 || " ") + '</td><td>' + (item.Defectsin2015 || " ") + '</td><td>'+
(item.DefectsasperBenchmarks || " ") +'</td><td>'+(item.costDefect || " ") + '</td><td>'+ (item.req2014 || " ") + '</td><td>'+ (item.req2015 || " ") +'</td><td>' +
(item.ba || " ") + '</td><td>'+ (item.config || " ")+'</td><td>'+ (item.Financials || " ") + '</td><td>' + (item.bReports || " ") + '</td><td>'+
(item.qa || " ") + '</td></tr>';
Set default value this way:
<td>'+ (item.req2015||' ') + '</td>
By filed setable defaults, easily reorganiziable:
var fdef = [ 'appnName '," "
,'Defectsin2014', " "
,'Defectsin2015'," "
,'costDefect ', " "
,'req2014 '," "
,'req2015 ', " "
,'ba '," "
,'config ', " "
,'Financials '," "
,'qa ', " "
];
function buildLine(item) {
var out = [];
for (var i= 0,l=fdef.length;i<l;++i) {
out.push(item[fdef[i][0]] || fdef[i][1]);
}
return '<tr><td>' + out.join('</td><td>') + '</td></tr>'
}
You can use this,
if(item.hasOwnProperty('req2015')){
//add it
}
Related
Below you see a ajax call that gets triggered when I press a button. Inside of the ajax call I append some'td' with value's to a table. On this line below: '</td><td>' + result[i].preRiskCategory + I'm trying to set the background color to a certain color when the value of preRiskCategory is above a certain number. Does anyone know if this is even possible and if so, how?
document.getElementById("searchButton").addEventListener("click", function (e) {
// vorige resultaten leegmaken.
clearTable();
if (id != "") {
$.post("/mainRiskanalysis/SearchMainRiskanalysisRisks?mainRiskanalysisId=" + id, function (result) {
for (let i = 0; i < result.length; i++) {
// Get risk-actionplan ids
getRiskActionplanIds(result[i].id);
// Looping through all ids and placing it in a string
for (j = 0; j < ids.length; j++)
idsString+=ids[j] + ", ";
//Get the names by id's
getZoneNameById(result[i].zoneId);
getEquipmentNameById(result[i].equipmentId);
getEquipmentTaskNameById(result[i].taskId);
getDangerNameById(result[i].dangerId);
getDangererousEnergieNameById(result[i].dangerousEnergiesId)
getConsequenceNameById(result[i].consequenceId);
// Getting the right table
var tbodyId = getTableId(result[i].categoryId);
$(tbodyId).append(
'<tr scope="row"><td><a class="text-primary" href="/riskanalysis/edit/' + result[i].id + '">Edit</a> | <a class="text-danger" href="/riskanalysis/delete/' + result[i].id + '">Delete</a>' +
'</td><td><a class="text-success" href="/riskActionPlan/create/' + result[i].id + '">Link actionplan</a>' +
'</td><td>' + idsString +
'</td><td style = "background-color: #C0C0C0">' + result[i].id +
'</td><td>' + zoneName +
'</td><td>' + equipmentName +
'</td><td>' + taskName +
'</td><td>' + result[i].activity +
'</td><td>' + result[i].action +
'</td><td>' + result[i].descriptionPotentialRisk +
'</td><td style="background-color: #99CC00">' + dangerName +
'</td><td>' + consequenceName +
'</td><td>' + dangerousEnergieName +
'</td><td style="background-color: #C0C0C0">' + result[i].preSeriousness +
'</td><td style="background-color: #C0C0C0">' + result[i].preProbability +
'</td><td style="background-color: #C0C0C0">' + result[i].preExposure +
'</td><td style="background-color: #C0C0C0">' + result[i].preRiskDegree +
'</td><td>' + result[i].preRiskCategory +
'</td><td>' + result[i].preventionMeasures +
'</td><td>' + result[i].safetyProcedures +
'</td><td>' + checkIfNull(result[i].postSeriousness) +
'</td><td>' + checkIfNull(result[i].postProbability) +
'</td><td>' + checkIfNull(result[i].postExposure) +
'</td><td>' + checkIfNull(result[i].postRiskDegree) +
'</td><td>' + checkIfNull(result[i].postRiskCategory) +
'</td><td>' + checkIfNull(result[i].improvementFactor) +
'</td><td>' + result[i].isOk +
'</td></tr>');
}
});
}
e.preventDefault()
});
Please let me know if you need further explaination of some sort.
Thanks!
Consider something like this:
'</td><td style="background-color: #C0C0C0">' + result[i].preRiskDegree +
'</td><td style="'+(
result[i].preRiskCategory > 100 ? 'background-color: orange;' : ''
)+'">' + result[i].preRiskCategory +
'</td><td>' + result[i].preventionMeasures +
You can concatenate a string that is either a background-color or an empty style using a ternary condition. Whitespace added for clarity.
I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .
I would like to clean this up with a For loop. What would be the most efficient way coding this out?
I'm creating a search form that looks through a database for the specific form criteria. The way I have it coded would only work for the 8 Fields. But it is possible for the search form to have more then 8. For now though, I'd like to be able to map the results and display in a results page.
This is what I tried. This did not work at all and probably make no sense to anyone lol.
var obj =data[0]
$.get("obj", {data: $('select["Fields.DisplayName" + Fields.DataValue]').val()},
function(data){
$.each(data, function(i, item) {
alert(item);
});
}
);
This works for getting the data and displaying it how I'd like.
var obj = data[0];
document.getElementById("test").innerHTML =
"<p>"+ obj.Fields[0].DisplayName + ": " + obj.Fields[0].DataValue + "</p>" +
"<p>" + obj.Fields[1].DisplayName + ": " + obj.Fields[1].DataValue + "</p>" +
"<p>"+ obj.Fields[2].DisplayName + ": " + obj.Fields[2].DataValue + "</p>" +
"<p>"+ obj.Fields[3].DisplayName + ": " + obj.Fields[3].DataValue + "</p>" +
"<p>" + obj.Fields[4].DisplayName + ": " + obj.Fields[4].DataValue + "</p>" +
"<p>" + obj.Fields[5].DisplayName + ": " + obj.Fields[5].DataValue + "</p>" +
"<p>"+ obj.Fields[6].DisplayName + ": " + obj.Fields[6].DataValue + "</p>" +
"<p>" + obj.Fields[7].DisplayName + ": " + obj.Fields[7].DataValue + "</p>"
;
The next problem is if there is more then 1 data object. Currently I have it set to loop through the first object, but when I remove that I get cannot read property of '0' undefined.
Sure.
var html = "";
obj.Fields.forEach(({DisplayName, DataValue}) => {
html += `<p>${DisplayName}: ${DataValue}</p>`;
});
document.getElementById("test").innerHtml = html;
Use Array.map() and join the results:
var fields = data[0].Fields ;
document.getElementById("test").innerHTML = fields
.map(function(field) {
return '<p>' + field.DisplayName + ': ' + field.DataValue + '</p>';
})
.join('\n');
Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read
This question already has answers here:
Can you have multiple lines in an <option> element?
(5 answers)
Closed 8 years ago.
I have here my jquery (coffeescript)
if value.kind != 'Quasi-Judicial'
if value.court_agency !in court_agency_with_branch
if value.court_agency != 'Department of Justice'
#court_agency = "<option value=\"" + value.id + "\"> Branch "+ value.branch_division + ", " + value.court_agency + ", " + #city_or_municipality + ", " + value.province + "</option>"
else
#court_agency = "<option value=\"" + value.id + "\">" + value.court_agency + ", " + #city_or_municipality + ", " + value.province + "</option>"
else
#court_agency = "<option value=\"" + value.id + "\"> Division "+ value.branch_division + ", " + value.court_agency + "</option>"
else
#court_agency = "<option value=\"" + value.id + "\">" + value.department + ", " + value.govt_agency + ", " + #city_or_municipality + ", " + value.province + "</option>"
on this part
"<option value=\"" + value.id + "\">" + value.department + ", " + value.govt_agency + ", " + #city_or_municipality + ", " + value.province + "</option>"
I want to put some code \n
"<option value=\"" + value.id + "\">" + value.department + ", " + "\n" + value.govt_agency + ", " + #city_or_municipality + ", " + value.province + "</option>"
but nothing happens.
The value looks like:
Department of Blah blah, City of This thing, Province of this stuff
What possible code I can use to create an output like this:
Department of Blah blah,
City of This thing,
Province of this stuff
Take a look at Can you have multiple lines in an <option> element?.
(What you're looking for is a br tag in an option tag)
Please refer this demo
http://shyalika.com/mutiline_select_example
you can find more information here:
http://shyalika.com/multiline_select_control