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)
}
}
})
}
}
})
}
})
}
})
Related
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>';
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 am facing issues while adding the options in the select that I am generating dynamically using jQuery. I am fetching options from the database and I want to show all those options for each dynamically generated select tag.
Please tell me what i am doing wrong in my code?
Here is my function to add new row :
function addnewrow() {
var n = ($('.detail tr').length - 0) + 1;
var tr = '<tr>' +
'<td class="no">' + n + '</td>' +
'<td><input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="prdct_till_check[' + till_check_counter + ']"></td>' +
'<td><select class="form-control barcode dyselect['+product_barcode_counter+']" name="barcode[' + product_barcode_counter + ']" id="prdct_barcode[' + product_barcode_counter + ']">'+'<option>Please select a bar code</option>'+'</select></td>' +
'<td><input type="text" class="form-control productname" id="brcode_product" name="productname[' + product_name_counter + ']" id="prdct_name[' + product_name_counter + ']"></td>' +
'<td><input type="text" class="form-control sm" name="sm[' + sm_counter + ']" id="prdct_sm[' + sm_counter + ']"></td>' +
'<td><input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="prdct_spl[' + spl_counter + ']"></td>' +
'<td><input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="prdct_qty[' + product_quantity_counter + ']"></td>' +
'<td><input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="prdct_price[' + product_price_counter + ']"></td>' +
'<td><input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="prdct_discount[' + product_discount_counter + ']"></td>' +
'<td><input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="prdct_amount[' + product_amount_counter + ']"></td>' +
'<td><a href="#" class="remove">Delete</td>' +
'</tr>';
$('.detail').append(tr);
//increamenting the counter
++till_check_counter;
++product_name_counter;
++product_quantity_counter;
++sm_counter;
++spl_counter;
++product_price_counter;
++product_discount_counter;
++product_amount_counter;
//setting the validation rules for every product attribute by calling the function
createValidation();
get_barcodes();
}
Here is the function for getting barcodes from database :
function get_barcodes() {
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: function(data) {
/*var obj = JSON.parse(data);
console.log(obj.brcode.name);*/
var myselect = $('.dyselect[' + product_barcode_counter + ']');
var barcodes = JSON.parse(data);
for (var i = 0; i < barcodes.brcode.length; i++) {
//console.log(barcodes.brcode[i].name);
//console.log(barcodes.brcode[i].barcode);
var options = ('<option value="' + barcodes.brcode[i].barcode + '">' + barcodes.brcode[i].barcode + '</option>');
console.log(options);
// $('.dyselect['+product_barcode_counter+']').append("Hello world");
$('.dyselect').text('dfsgfisdgfsiudfgsdf');
}
}
});
}
Please do not consider the commented code.
You are not appending your options to the DOM anywhere.
myselect.append(options); // Missing this line
You are incrementing your ++product_barcode_counter after adding a row
//increamenting the counter
++till_check_counter;
++product_name_counter;
++product_quantity_counter;
++sm_counter;
++spl_counter;
++product_price_counter;
++product_discount_counter;
++product_amount_counter;
so, by the time you are accessing the product_barcode_counter inside the ajax success its incremented.
Here,
your var myselect = $('.dyselect_' + product_barcode_counter); selection is wrong it is returning nothing.
You have to bind your id to the ajax so that you can read the value on ajax success.
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: function(id,data) {
//Here id is what you need to use to select the correct select.
}.bind(this,product_name_counter-1)
);
JS
function get_barcodes() {
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: function(id,data) {
var myselect = $('.dyselect_' + id);
var barcodes = JSON.parse(data);
for (var i = 0; i < barcodes.brcode.length; i++) {
var options = ('<option value="' + barcodes.brcode[i].barcode + '">' + barcodes.brcode[i].barcode + '</option>');
myselect.append(options); // Missing this line
}
}.bind(this,product_name_counter-1)
});
}
OR you can use closure
success: (function(id){
return function(data) {
//Here id is what you need to use to select the correct select.
}
})(product_name_counter-1);
JS
function get_barcodes() {
$.ajax({
url: 'http://localhost/retail/main/ajax_barcodes/',
type: 'POST',
datatype: 'json',
data: {
'barcode': $('#brcode option:selected').val()
},
success: (function(id){
return function(data) {
var myselect = $('.dyselect_' + id);
var barcodes = JSON.parse(data);
for (var i = 0; i < barcodes.brcode.length; i++) {
var options = ('<option value="' + barcodes.brcode[i].barcode + '">' + barcodes.brcode[i].barcode + '</option>');
myselect.append(options); // Missing this line
}
}
}
})(product_name_counter-1);
});
}
I have nested callabcks but resulted output is not ordered correctly. My ajax results are in ascending orders of id but html generated is random. can someone help me out pls?
var formatedhtml = '';
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
console.log(value);
getdetails(value['id'], function(output) {
formatedhtml = formatedhtml +
'<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + value['id'] + '</div>' +
'<div class="tableno">' + value['tableno'] + '</div>' +
'<div class="ordertype">' + value['type'] + '</div>' +
'<div class="timestamp">' + value['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(output['items']), function(k, val) {
formatedhtml = formatedhtml + '<div class="row">' +
'<div class="quantity">' + val[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
formatedhtml = formatedhtml +
'<div class="row">' +
'<div class="notes">' + value['id'] + '</div>' +
'</div>' +
'</div>';
$("#orderlist").html(formatedhtml);
console.log(output);
});
});
}
});
edit:
Here is getdetails function. its an ajax request.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: id,
},
success: function(data) {
callback(data[0]);
}
});
};
There are a lot of ways to achieve this, one is to use a promise and sort by id when all requests are done. Another you could create the template and append the details on callback as each detail request has an id you can define in your template a class like 'id-'+value['id'] and use jquery selector and append detail template.
Another solution would be to create a function loop that calls itself untill orderCount == orderLoaded.
Job is done synchronously (takes more time)
//Mock ajax function
$.ajax = function (param) {
if(param.url.indexOf('readdetails') != -1){
param.success(itemsData);
} else {
param.success(ordersData);
}
};
//Mock data
var ordersData = [
{ id : 1, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 2, tableno : 'xyz', type: 'invoice', created: '01/01/2001' },
{ id : 3, tableno : 'xyz', type: 'invoice', created: '01/01/2001' }
];
var itemsData = [
{ id : 1, orderid: 1, quantity: 5 },
{ id : 2, orderid: 1, quantity: 2 },
{ id : 3, orderid: 1, quantity: 1 }
];
// Globals
var formatedhtml = [];
var orders = [];
var lastOrderLoaded = 0;
var BASE_URL = 'localhost/';
function tpl(order, items) {
var html = '<tr class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <td class="orderno">' + order['id'] + '</td>' +
'<td class="tableno">' + order['tableno'] + '</td>' +
'<td class="ordertype">' + order['type'] + '</td>' +
'<td class="timestamp">' + order['created'] + '</td>' +
' </tr>';
$.each(items, function(key, item) {
html += '<tr class="row">' +
'<td class="item">item: ' + item.id + '</td>' +
'<td class="quantity">quantity: ' + item.quantity + '</td>' +
'</tr>';
});
html +=
'<tr class="row">' +
'<td class="notes"> notes </td>' +
'<td class="notes"> order id ' + order['id'] + '</td>' +
'</tr>' +
'</tr>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
lastOrderLoaded = 0;
orders = data;
getdetails(orders[0]);
}
});
function getdetails(order) {
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
tpl(order, data);
if(lastOrderLoaded < orders.length - 1){
lastOrderLoaded++;
getdetails(orders[lastOrderLoaded]);
} else {
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
}); // end each
}
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="orderlist" border="1">
<tr><th>id</th><th>no</th><th>type</th><th>date</th></tr>
</table>
Promise Solution:
Job is done asynchronously (might take less time also bombards the server with many requests at once)
var formatedhtml = [];
function tpl(order, items) {
var html = '<div class="col-md-4 col-sm-4 col-lg-3 col-xs-6">' +
' <div class="row">' +
' <div class="orderno">' + order['id'] + '</div>' +
'<div class="tableno">' + order['tableno'] + '</div>' +
'<div class="ordertype">' + order['type'] + '</div>' +
'<div class="timestamp">' + order['created'] + '</div>' +
' </div>' +
'<hr>';
$.each(JSON.parse(items['items']), function(key, item) {
var html += '<div class="row">' +
'<div class="quantity">' + item[3] + '</div>' +
'<div class="item">' + '</div>' +
'</div>';
});
html +=
'<div class="row">' +
'<div class="notes">' + order['id'] + '</div>' +
'</div>' +
'</div>';
formatedhtml.push({ id: order.id, html : html });
}
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/read',
dataType: 'json',
success: function(data) {
var syncLoad = [];
$.each(data, function(key, value) {
syncLoad.push(getdetails(value, tpl));
});
$.when.apply($, syncLoad).done(function() {
formatedhtml.sort(function(a, b){
return a.id - b.id;
});
formatedhtml.forEach(function(element){
$("#orderlist").append(element.html);
});
});
}
});
function getdetails(order, callback) {
return $.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
data: {
id: order.id,
},
success: function(data) {
callback(order, data[0]);
}
});
};
Use async:false in your getDetails() ajax call.
function getdetails(id, callback) {
var result;
$.ajax({
type: "POST",
url: BASE_URL + 'index.php/orders/readdetails',
dataType: 'json',
async: false,
data: {
id: id,
},
success: function (data) {
callback(data[0]);
}
});