Change color related on value - javascript

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");
}

Related

Codigniter Javascript nested Jquery error

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)
}
}
})
}
}
})
}
})
}
})

While generating table to division unexpected code generated from jquery

hello i am trying to add table in division when date is shown ...all perform okay ..but in division an unwanted code generate like [object Object],[object Object]...i want to remove that code.
$(document).ready(function () {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
$('#DT').val(today);
$.fn.ABC = function () {
var selectedValue = $("#DT").val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWaxAss")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'SelectedDate': selectedValue }),
success: function (waxAsslist) {
if (Object.keys(waxAsslist).length > 0) {
$('#detailtbl').text("");
$('#detailtbl').append('<div class="card">' +
'<div class="card-header card-header-primary card-header-icon">' +
'<div class="card-icon"><i class="material-icons">assignment</i>' +
'</div><h4 class="card-title">Wax Assembly List</h4></div>' +
'<div class="card-body">' +
'<div class="material-datatables">' +
'<table id="datatables" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">' +
'<thead>' +
'<tr>' +
'<th><b>PRC No</b></th>' +
'<th><b>Die No</b></th>' +
'<th><b>Description</b></th>' +
'<th><b>Metal</b></th>' +
'<th><b>Qty</b></th>' +
'<th><b>Reject Qty</b></th>' +
'<th><b>Shell</b></th>' +
'<th><b>Total Weight</b></th>' +
'<th><b>User</b></th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
$.each(waxAsslist, function (i, data) {
setTimeout(function () {
$('#datatables tbody').append(
'<tr>'
+ '<td>' + data.PRCNO + '</td>'
+ '<td>' + data.MOULDCODE + '</td>'
+ '<td>' + data.DESCRIPTION + '</td>'
+ '<td>' + data.METALNAME + '</td>'
+ '<td>' + data.Qty + '</td>'
+ '<td>' + data.RejectQty + '</td>'
+ '<td>' + data.Shell + '</td>'
+ '<td>' + data.TotalWt + '</td>'
+ '<td>' + data.USERNAME + '</td>'
+ '</tr>'
)
}, 1000);
}),
'</tbody>' +
'</table>' +
'</div>' +
'</div>' +
'</div>');
}
},
error: function () { alert('Error. Please try again.'); }
});
};
$.fn.ABC();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<input type="date" id="DT">
</div>
<div class="row">
<div class="col-md-12" id="detailtbl">
</div>
</div>
here is my controller where from my data came.
[HttpPost]
public ActionResult DateWiseData(DateTime SelectedDate)
{
var Dw = DateTime.Now.ToShortDateString();
var idparam = new SqlParameter
{
ParameterName = "date",
Value = SelectedDate
};
var waxAsslist = Db.Database.SqlQuery<spDataWaxAss>("exec sp_PRCWax_Assembly_Get_Date #date", idparam).ToList();
return Json(waxAsslist, JsonRequestBehavior.AllowGet);
}
return json value like this
json return value
in output it will be show like this ...
output generate like this
i want to remove yellow highlighted portion ...i don't know from where it generate...
can any one help me..

Depend on the popup's table data, parent's table data showing item is different

I have a popup modal like this one.
When I click 'ADD' button, all the data from popup's table is shown at the table of the parent's. Like this one.
The problem is that I don't want to show the plus sign "+", if there is no data in textbox2s.
Here is the code at popup.js
function add_to_prent_table(){
var popupTable = [];
var i = 0;
$('#testing > tbody > tr').each(function () {
popupTable[i] = [
$(this).find("#test_number").val(),
$(this).find("#type_1").val(),
$(this).find("#type_2").val(),
$(this).find("#place_1").val(),
$(this).find("#place_2").val(),
];
i++;
var newRow = '<tr>'+
'<td id ="td_center">'+
$(this).find("#test_piece_number").val() +
'</td>'+
'<td id ="td_center">'+
$(this).find("#type_1").val() + ' + ' +
$(this).find("#type_2").val() +
'</td>'+
'<td id ="td_center">'+
$(this).find("#place_1").val() + ' + ' +
$(this).find("#place_2").val() +
'</td>'+
'</tr>';
$('#testing_parent tbody').append(newRow);
});
}
How can I fix this?
It's messy but you can replace the first ' + ' with this:
$(this).find("#type_2").val() ? ' + ' : ''
And replace the second ' + ' with
$(this).find("#place_2").val() ? ' + ' : ''
Basically you're looking to see if #type_2 and #place_2 have values. If they do, add a ' + '. If not, add nothing.
Try this;
function add_to_prent_table() {
var popupTable = [];
var i = 0;
$('#testing > tbody > tr').each(function () {
var testNumber = $(this).find("#test_number").val();
var firstType = $(this).find("#type_1").val();
var secondType = $(this).find("#type_2").val();
var firstPlace = $(this).find("#place_1").val();
var secondPlace = $(this).find("#place_2").val();
popupTable[i] = [
testNumber,
firstType,
secondType,
firstPlace,
secondPlace,
];
i++;
var newRow = '<tr>' +
'<td id ="td_center">' +
$(this).find("#test_piece_number").val() +
'</td>' +
'<td id ="td_center">' +
firstType + secondType ? (' + ' + secondType) : '' +
'</td>' +
'<td id ="td_center">' +
firstPlace + secondPlace ? (' + ' + secondPlace) : '' +
'</td>' +
'</tr>';
$('#testing_parent tbody').append(newRow);
});
}
Simply you can add condition before adding plus sign like below,
var newRow = '<tr>'+
'<td id ="td_center">'+
$(this).find("#test_piece_number").val() +
'</td>'+
'<td id ="td_center">'+
$(this).find("#type_1").val()
if($(this).find("#type_2").val() != "")
{
' + ' + $(this).find("#type_2").val()
}
'</td>'+
'<td id ="td_center">'+
$(this).find("#place_1").val()
if($(this).find("#place_2").val() != "")
{
' + ' + $(this).find("#place_2").val()
}
'</td>'+
'</tr>';

how to change one button based on value

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>';

Error: Cannot read property 'each' of undefined

I have a JavaScript code that returns values of a PHP and assembles an HTML table. Is giving the error can not read property of each undefined. I've looked several times without success. They could give me a hand?
The following code:
JavaScript:
function getListaItems(idprojeto) {
//alert(idprojeto);
jQuery.ajax({
type: "POST",
url: "get-lista-items.php?idprojeto=" + idprojeto,
//data: dataEvento,
dataType: 'json',
success: function(resposta) {
var str_html = '';
$.each(resposta, function(){
str_html = str_html + '<tr class="gradeA" id="' + this.id + '">' +
'<td class="center"><input type="checkbox" id="item[]" name="item[]" onchange="changeColor(' + this.id + ')" value="' + this.id + '" /></td>' +
'<td class="center">' + this.descricao + '</td>' +
'<td class="center">' + this.descCategoria + '</td>' +
'<td class="center">' + this.descCaracteristica + '</td>' +
'<td class="center">' + this.descMedida + '</td>' +
'<td class="center"><input type="text" id="qtd' + this.id + '" style="width:80px"/></td>' +
'</tr>';
});
document.getElementById("resultJs").innerHTML = str_html;
}
});
}
PHP:
<?php
session_start();
require_once("ProjectIncludes.php");
$service = new ProjetoxItensService();
$consulta = $service->getAll($_GET['idprojeto']);
$retorno = json_encode($consulta);
echo $retorno;
?>
Thanks, guys.
Looks like jQuery is not available using $, try jQuery instead.
Change this line:
$.each(resposta, function(){
to this:
jQuery.each(resposta, function(){

Categories