I want to change my ajax button based on if else condition. Like if status is 1 then it will show just active button otherwise it just show the inactive button. I have two buttons. I cant find the logic where I actually put my if else condition. My code is:
function showAllArticle(status = "") {
//alert(status);
$.ajax({
//cache: false,
//headers: { "cache-control": "no-cache" },
type: 'ajax',
method: 'post',
data: {
status: status
},
url: '<?php echo base_url() ?>Article/showAllUser',
async: true,
dataType: 'json',
//cache: false,
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
//(data[i].status);
html += '<tr>' +
'<td>' + data[i].id + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].email + '</td>' +
'<td>' +
// '{% if data[i].status == 1 %}'
'Active' +
//#if(data[i].status == 1)
//'{% else %}'
'Inactive' +
//'{% endif %}'
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get Data from Database');
}
});
}
You must apply the if condition based on JS, not on the template language you are using as JS is executed on the user end.
You must do something similar do this:
html += '<tr>';
html += '<td>' + data[i].id + '</td>';
html += '<td>' + data[i].username + '</td>';
html += '<td>' + data[i].email + '</td>';
html += '<td>';
if (data[i].status == 1) {
html += 'Active';
} else if(data[i].status == 12) {
//...
} else {
html += 'Inactive' +
}
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
html += '</tr>';
Related
Below I have the code for my HTML table that is created from an ajax request pulling SharePoint list items. In the screenshot it shows how it works and what it displays after the button is clicked. How do I get my table to load without having to click the button that way when I load the page it is already displayed?
Secondly, how can I get rid of the header rows when it pulls from the second list since the information data is pulled from lists with the same items. I would much rather have a column on the side showing which list the rows are from instead.
Any suggestions?
Table in Action
AFter edit
https://i.stack.imgur.com/IXEWn.png
<script src="/Scripts/jquery-3.3.1.min.js"></script>
<input type="button" id="btnClick" value="Get Employee Information" />
<div id="EmployeePanel">
<table id='employeeTab' style="width: 100%;" border="1 px">
<tr>
<td>
<div id="employees" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
$(function() {
$("#btnClick").click(function() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
$.ajax({
url: fullUrl1,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' + '</tr></thead><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title + '</td>';
tableContent += '<td>' + objItems[i].Age + '</td>';
tableContent += '<td>' + objItems[i].Position + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].Education + '</td>';
tableContent += '<td>' + objItems[i].Degree + '</td>';
tableContent += '</tr>';
}
$('#employees').append(tableContent);
}
function onError(error) {
alert('Error');
}
});
});
make table in your html
<input type="button" id="btnClick" onclick="load_table_function()" value="Get Employee Information" />
<div id="EmployeePanel">
<div id="employees" style="width: 100%">
<table id="employeeTab" style="width:100%" border="1 px">
<thead>
<tr>
<td><strong>Name</strong></td>
<td><strong>Age</strong></td>
<td><strong>Position</strong></td>
<td><strong>Office</strong></td>
<td><strong>Education</strong></td>
<td><strong>Degree</strong></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
changes in js
function load_table_function() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
$.ajax({
url: fullUrl1,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title + '</td>';
tableContent += '<td>' + objItems[i].Age + '</td>';
tableContent += '<td>' + objItems[i].Position + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].Education + '</td>';
tableContent += '<td>' + objItems[i].Degree + '</td>';
tableContent += '</tr>';
}
$('#employeeTab tbody').append(tableContent);
}
}
and for on load
$(document).ready(function () {
load_table_function();
}
Your JS code must be on window's load listener, that means when the page gets loaded.
$(function() {
window.addEventListener('load', function() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
var firstResp = [];
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: firstrequestHandler,
error: onError
});
function firstrequestHandler(aFirstReqResponse) {
firstResp = aFirstReqResponse;
$.ajax({
url: fullUrl1,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
}
function onSuccess(data) {
data = firstResp.concat(data);
var objItems = data.d.results;
var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' + '</tr></thead><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title + '</td>';
tableContent += '<td>' + objItems[i].Age + '</td>';
tableContent += '<td>' + objItems[i].Position + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].Education + '</td>';
tableContent += '<td>' + objItems[i].Degree + '</td>';
tableContent += '</tr>';
}
$('#employees').append(tableContent);
}
function onError(error) {
alert('Error');
}
});
});
Create the table headers under table content, then append to the table.
var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' + '</tr></thead><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title + '</td>';
tableContent += '<td>' + objItems[i].Age + '</td>';
tableContent += '<td>' + objItems[i].Position + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].Education + '</td>';
tableContent += '<td>' + objItems[i].Degree + '</td>';
tableContent += '</tr>';
}
$('#employees').append(tableContent);
}
My requirnment is if data1[count1].result_type > 0 then the td will be a drop down list from a datatable. Nut is i try this, the output is like this, all the required options are comming to a single selectbox insted of the relevent row. And the result comes to the very last row.
The desired result would be two dropdowns at the last two rows. The wanted result options all together in the one dropdown. How can I solve this?
$('#bill_no_search').click(function() {
{
$("#data_table_one tbody").html("");
var barcode = $('#barcode_no').val();
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/get_barcode_to_bill_no'); ?>",
data: {
barcode: barcode
},
method: "POST",
dataType: "JSON",
success: function(data) {
var bill_no = data.bill_no;
console.log(bill_no)
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/resulting'); ?>",
data: {
bill_no: bill_no
},
method: "POST",
dataType: "JSON",
success: function(data) {
for (var count = 0; count < data.length; count++) {
var element_id = data[count].element_id;
var ct = 'screen' + count + '';
var bt = 'td' + count + ''
var result = 'result' + count + ''
$('#data_table_one tbody').append(
'<tr>' +
'<td >' + (count + 1) + '</td>' +
'<td >' + data[count].billing_element_result_id + '</td>' +
'<td >' + data[count].bill_no + '</td>' +
'<td >' + data[count].processor_id + '</td>' +
'<td >' + data[count].test_processor_display_name + '</td>' +
'<td >' + data[count].test_code + '</td>' +
'<td >' + data[count].test_details + '</td>' +
'<td contenteditable=true id="result' + count + '">' + data[count].result + '</td>' +
'<td id="td' + count + '" contenteditable=true><select id="screen' + count + '" style="display:none"></select></td>' +
'<td contenteditable=true id="resultcell">' + data[count].result + '</td>' +
'</tr>'
);
console.log(ct)
$.ajax({
url: "<?php echo base_url('index.php/Lab_and_lab_office/get_result_type'); ?>",
data: {
element_id: element_id
},
method: "POST",
dataType: "JSON",
success: function(data1) {
for (var count1 = 0; count1 < data1.length; count1++) {
if (data1[count1].result_type > 0) {
document.getElementById(ct).style.display = "block";
$('#' + ct + '').append(
'<option>' + data1[count1].result_options + '</option>'
);
document.getElementById(bt).contentEditable = "false";
document.getElementById(result).contentEditable = "false";
}
console.log(ct)
}
}
})
}
}
})
}
})
}
})
I have table values populated from back-end
Here is js function that doing it.
function AllProposals() {
let getProposalsUrl = '/proposals/index';
$.ajax({
url: getProposalsUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#proposals").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' +
'<td class="proposalId">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Project +
'</td>' +
'<td > ' +
moment(list[i].DateFrom).format('DD/MM/YYYY') + "--" + moment(list[i].DateTo).format('DD/MM/YYYY') +
'</td>' +
'<td> ' +
list[i].WorkTime + "--" +list[i].WorkTimeTo +
'</td>' +
'<td > ' +
list[i].Quantity+
'</td>' +
'<td> ' +
list[i].Service +
'</td>' +
'<td> ' +
list[i].Price +
'</td>' +
'<td> ' +
list[i].Status +
'</td>' +
'</tr>';
$('#proposals').append(tableData);
}
}
})
}
It working great.
Bu It need to check this value on flight
'<td> '+list[i].Status+'</td>' +
And if it is "Rejected" change text color to red.
How I can do this correctly?
Thank's for help.
Assuming that this code will need some refactoring if you will need to reuse the return data of the ajax call and in general it is not good looking, I would do as follows:
'<td'+ (list[i].Status == 'Rejected' ? ' style="color:red;"' : '') +'> ' +
list[i].Status +
'</td>' +
Edit
If in future you will need to assign different colors based on the content of list[i].Status, I suggest to create a content-to-color lookup table:
let contentToColor = {
"Rejected": "red",
"Success": "green",
"Warning": "yellow"
};
and then:
'<td'+ (contentToColor[list[i].Status] !== 'undefined' ? ' style="color: '+ contentToColor[list[i].Status] +';"' : '') +'> ' +
list[i].Status +
'</td>' +
The way of checking the existence of the variable may be wrong, I don't remember how it is done in JS, but you get the concept.
Anyway, I would suggest to refactor the code by separating the presentation code and the domain code. You will save yourself by the ugly code I wrote above. I had to read it 10 times for checking if the quotes were good.
You can use a switch to get the status and set the color base on what you get and pass it to a variable.
Example
<script>
function AllProposals() {
let getProposalsUrl = '/proposals/index';
$.ajax({
url: getProposalsUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#proposals").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var mycolor = "";
switch (list[i].Status) {
case "Approved":
mycolor = "style="color:green";
break;
case "Rejected":
mycolor = "style="color:red";
//Add more if needed
}
var tableData = '<tr>' +
'<td class="proposalId">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Project +
'</td>' +
'<td > ' +
moment(list[i].DateFrom).format('DD/MM/YYYY') + "--" + moment(list[i].DateTo).format('DD/MM/YYYY') +
'</td>' +
'<td> ' +
list[i].WorkTime + "--" +list[i].WorkTimeTo +
'</td>' +
'<td > ' +
list[i].Quantity+
'</td>' +
'<td> ' +
list[i].Service +
'</td>' +
'<td> ' +
list[i].Price +
'</td>' +
'<td' + mycolor +'> ' +
list[i].Status +
'</td>' +
'</tr>';
$('#proposals').append(tableData);
}
}
})
}
</script>
You can use alter the style attribute using jQuery's .attr method (http://api.jquery.com/attr/)
if(status=="rejected"){
$(.elementclass).attr("style","color:red");
}
I have a javascript function that renders a table from an ajax call.
The row rendering bit is:
function buildTable(id) {
trHTML = null;
$.ajax({
type: "GET",
url: siteroot + "apiURL" + id,
data: {},
dataType: "json",
cache: false,
success: function (data) {
for (i = 0; i < data.length; i++) {
trHTML +=
'<tr>' +
'<td>' + data[i].value +
'<a class="pull-right" href="#" data-toggle="modal" data-target="#edit-modal" > ' +
'<span class="pull-right glyphicon glyphicon-pencil"></span>' +
'</a>' +
'</td>' +
'<td>' + data[i].text + '</td>' +
'<td>' + data[i].description + '</td>' +
'</tr>';
}
$('#resourceTable').append('<tbody>' + trHTML + '</tbody>');
},
error: function (msg) {
alert(msg.responseText);
}
});
}
And the modal is defined as:
<div th:replace="../../modals/modal"></div>
The issue I am facing is that the link is here on the rendered table, but when I click it, the modal does not come on.
What am I not seeing here?
I worked on this sample for 3 days strucked at last step!! Please some one help me!!
Any Help is appreciable!!
I am loading a dynamic table, i want to attach a grid on a column. I created a function for binding jqgrid. So when ever i am binding a table i am calling this function with a parameter,
The problem here is if i give the parameter directly it is working , but if i want to load it automatically it is not working.
I will explain below with code:
function bindData() {
$.ajax({
type: "POST",
url: location.pathname + "/getData",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
var msg = eval('(' + response.d + ')');
if ($('#tblResult').length != 0) // remove table if it exists
{ $("#tblResult").remove(); }
var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>SurName</th><th>Email</><th>Mobile</th><th>Address</th><th>Actions</th><th>image</th><th>Country</th><th>State</th><th>Gender</th><th>Add.Mobile</th></thead><tbody>";
for (var i = 0; i <= (msg.length - 1); i++) {
var row = "<tr>";
row += '<td>' + msg[i].Name + '</td>';
row += '<td>' + msg[i].SurName + '</td>';
row += '<td>' + msg[i].Email + '</td>';
row += '<td>' + msg[i].Mobile + '</td>';
row += '<td>' + msg[i].Address + '</td>';
row += '<td><img id="im" src="/User_Registration1/images/edit.png" title="Edit record." onclick="bindRecordToEdit(' + msg[i].EmployeeId + ')" /> <img src="/User_Registration1/images/delete.png" onclick="deleteRecord(' + msg[i].EmployeeId + ')" title="Delete record." /></td>';
row += '<td><img class="img" src=' + msg[i].FileName + ' alt="--NO IMAGE--"/></td>';
row += '<td>' + msg[i].Country + '</td>';
row += '<td>' + msg[i].StateName + '</td>';
row += '<td>' + msg[i].Gender + '</td>';
row += '<td style="width:250px;height:120px;"><table id="tblSub' + msg[i].Name + '"></table><script> $(document).ready(function () { BindGrid("AjjiAjji");});</script></td>';
row += '</tr>';
table += row;
}
table += '</tbody></table>';
$('#divData').html(table);
$("#divData").slideDown("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
see the last column in which i am attaching a grid view by calling a javascript function.
js function:
function BindGrid(user) {
$(document).ready(function () {
$("#tblSub"+user).jqGrid({
loadError: function (xhr, status, error) {
alert('load:' + error);
},
url: 'Fetch.aspx?filter=' + user + '',
data: "{}",
datatype: 'json',
colNames: ['Name', 'Mobile'],
colModel: [
{
name: 'User',
index: 'User',
width: 100,
align: "left",
editable: true,
size: 80
},
{
.
.
.
So if i pass the BindGrid("AjjiAjji") it is working fine, But i want to load the grid automatically like BindGrid('+msg[i].Name+') , It is Showing Error "ReferenceError: AjjiAjji is not defined"
I think you are forgetting to add double quotes and the result whould be BindGrid (AjjAjj). try this:
BindGrid("'+msg[i].Name+'")
this should work fine
I think that problem is that the time you are attaching jqGrid to "$("#tblSub"+user)" is not present in DOM.
You should call BindGrid function only after $('#divData').html(table); which is adding table into DOM.
So that jqGrid can properly work.