Error: Cannot read property 'each' of undefined - javascript

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(){

Related

how to check if a html table has duplicated rows in js and sum inputs instead of insert another row?

I'm learning JS while doing a POS System, and I'm having a hard time trying to figure out how to check if the product added is already scanned before inserting and if so, change the quantity input instead.
So far when I scan the product id it inserts without a problem, but when I scan the same id it inserts in a new row. It seem that my function comprobacion isn't working. I tried with other using a for to search in the rows, and I tried some solutions that I found online but nothing seems to work.
here is an example of what its happening
https://gfycat.com/respectfultemptingeastrussiancoursinghounds
idProductos is the primary key and is hidden in the rows, so im introducing codigo (it's another unique column, both cannot be null).
Can someone help me? I'm lost.
This is my code
$.ajax({
method: "POST",
url: "../php/venta.php",
data: param,
success: function(data) {
if (data != null) {
var idProductos,
Codigo,
nombre,
precioVenta;
// console.log(data);
var rows = jQuery.parseJSON(data);
idProductos = rows[0].idProductos;
Codigo = rows[0].Codigo;
nombre = rows[0].nombre;
precioVenta = rows[0].precioVenta;
(idProductos)
if (comprobacion(idProductos) == false) {
var nuevoValor = $(parseInt($('.inputCantidad')[i]).val()) + 1;
$($('.inputCantidad')[i]).val(nuevoValor);
var valorImporte = $($('.inputprecioVenta')[i]).val() * nuevoValor;
$($('.inputImporte')[i]).val(valorImporte);
} else {
var table = document.getElementById('tablaVenta');
var newRow = document.createElement("tr");
newRow.align = "center";
var contentRow =
'<td><input type="hidden" class="inputId" value="' + idProductos + '">' + Codigo + '</td>' +
'<td>' + nombre + '</td>' +
'<td><input class="inputprecioVenta" value="' + precioVenta + '"></td>' +
'<td><input class="inputCantidad" value="1"></td>' +
'<td><input class="inputImporte" value="' + precioVenta + '"></td>';
newRow.innerHTML = contentRow;
table.appendChild(newRow);
}
}
},
error: function(jqXHR, textStatus, errorThrown) { //errores
alert(jqXHR + textStatus + errorThrown);
},
})
}
the function comprobacion
function comprobacion(idProductos) {
var id = $(idProductos).val();
$('tbody tr').each(function() {
if ($(this).val() == id) {
return false;
}
});
return true;
}
I would add the id to the row using a custom data attribute, like data-id, and use that, along with some clever selector creation to quickly identify if the id has been used before.
$.ajax({
method: "POST",
url: "../php/venta.php",
data: param,
success: function(data) {
if (data != null) {
var idProductos,
Codigo,
nombre,
precioVenta;
// console.log(data);
var rows = jQuery.parseJSON(data);
idProductos = rows[0].idProductos;
Codigo = rows[0].Codigo;
nombre = rows[0].nombre;
precioVenta = rows[0].precioVenta;
(idProductos)
if (comprobacion(idProductos) == false) {
var nuevoValor = $(parseInt($('.inputCantidad')[i]).val()) + 1;
$($('.inputCantidad')[i]).val(nuevoValor);
var valorImporte = $($('.inputprecioVenta')[i]).val() * nuevoValor;
$($('.inputImporte')[i]).val(valorImporte);
} else {
var table = document.getElementById('tablaVenta');
var newRow = document.createElement("tr");
newRow.align = "center";
/* Add the line below */
newRow.setAttribute("data-id", idProductos);
var contentRow =
'<td><input type="hidden" class="inputId" value="' + idProductos + '">' + Codigo + '</td>' +
'<td>' + nombre + '</td>' +
'<td><input class="inputprecioVenta" value="' + precioVenta + '"></td>' +
'<td><input class="inputCantidad" value="1"></td>' +
'<td><input class="inputImporte" value="' + precioVenta + '"></td>';
newRow.innerHTML = contentRow;
table.appendChild(newRow);
}
}
},
error: function(jqXHR, textStatus, errorThrown) { //errores
alert(jqXHR + textStatus + errorThrown);
},
})
Then, the comprobacion function becomes easier:
function comprobacion(idProductos) {
return $('tbody tr[data-id="' + idProductos + '"]').length === 0;
}
Set id to HTML inputs, is more quick to find ProductID with JS.
'<td><input type="hidden" id="hid_' + idProductos + '" class="inputId" value="' + idProductos + '">' + Codigo + '</td>' +
'<td>' + nombre + '</td>' +
'<td><input id="hid_' + idProductos + '" class="inputprecioVenta" value="' + precioVenta + '"></td>' +
'<td><input id="qty_' + idProductos + '" class="inputCantidad" value="1"></td>' +
'<td><input id="cst_' + idProductos + '" class="inputImporte" value="' + precioVenta + '"></td>';
Try $('tbody tr td').each(function().
The value is in the td, not the tr

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

Change color related on value

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

How to get ajax response on a button click

I am getting table data from ajax response as json.Some json datas am not displaying but I want it on a button click for other purpose.How can I get it?Please help me.
function leaveTable() {
for (var i = 0; i < leaveList.length; i++) {
var tab = '<tr id="' + i + '"><td>' + (i + 1) + '</td><td class="appliedOn">' + leaveList[i].appliedOn + '</td><td class="levType" >' + leaveList[i].levType + '</td><td class="leaveOn" >' + leaveList[i].leaveOn + '</td><td class="duration">' + leaveList[i].duration + '</td><td class="status">' + leaveList[i].status + '</td><td class="approvedOn">' + leaveList[i].approvedOn + '</td><td class="approvedBy">' + leaveList[i].approvedBy + '</td><td><i class="btn dltLev fa fa-times" onclick="cancelLeave(this)" data-dismiss="modal" value="Cancelled"></i></td><tr>';
$('#levListTable').append(tab)
}
}
from ajax response I want leaveTypeId and pass it into sendCancelReq() function.
Complete code :https://jsfiddle.net/tytzuckz/18/
It is complicated to know exactly what you want. I hope that helps you:
The first, I would change, is not to produce the JavaScript events in your html code var tab = .... I think, it is more clear and readable, when you add your event after the creation of the new dom elements. For example:
var tab = $('<tr id="' + i + '">' +
'<td>' + (i + 1) + '</td>' +
'<td class="appliedOn">' + leaveList[i].appliedOn + '</td>' +
'<td class="levType" >' + leaveList[i].levType + '</td>' +
'<td class="leaveOn" >' + leaveList[i].leaveOn + '</td>' +
'<td class="duration">' + leaveList[i].duration + '</td>' +
'<td class="status">' + leaveList[i].status + '</td>' +
'<td class="approvedOn">' + leaveList[i].approvedOn + '</td>' +
'<td class="approvedBy">' + leaveList[i].approvedBy + '</td>' +
'<td><i class="btn dltLev fa fa-times" data-dismiss="modal" value="Cancelled"></i></td>' +
'<tr>');
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this); });
Then, you are able to send your necessary information more clearly, e.g.:
Instead of the last code
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this); });
you can write
$(tab).find('.btn.dltLev').click(function () { cancelLeave(this, leaveList[i].leaveTypeId); });
and extend your method cancelLeave to:
function cancelLeave(elem, leaveTypeId) {
var id = $(elem).closest('tr').attr('id')
alert(id)
$("#cancelLeave").modal("show");
$('.sendCancelReq').val(id);
sendCancelReq(leaveTypeId);
}
Got solutionPlease check this:https://jsfiddle.net/tytzuckz/19/
function cancelLeave(elem) {
var levTypeId = $(elem).attr('id')
var id = $(elem).closest('tr').attr('id')
$('.currentLevTypeId').val(levTypeId);
$("#cancelLeave").modal("show");
$('.sendCancelReq').val(id);
}
function sendCancelReq() {
var a= $('.currentLevTypeId').val();
alert(a)
}

Errors in js function that builds a table row

I am building a table row in a jQuery $.ajax() call that builds a row on successful execution of a PHP script.
I'm calling a function that builds a new table row based on the script results. Here is the function:
function addNewRow(addDocs, newClassID, classNumberAdd, classNameAdd) {
var newRow = '';
newRow += $('#classesTable tbody:last').after('<tbody>' +
'<tr bgcolor="#EFE5D3" style="font-weight: bold;">' +
'<td width="35px"><a class="classEditLink" name="' + newClassID + '" href="#">Edit</a></td>' +
'<td width="20px"><input type="checkbox" class="chkSelectToDelete" name="deleteClasses[]" value="' + newClassID + '" /></td>' +
'<td>' + classNumberAdd + '</td>' +
'<td>' + classNameAdd + '</td>' +
'</tr>');
if (addDocs == 'true') {
$('#docsTable input[type="checkbox"]:checked').each(function() {
var $row = $(this).parents('tr');
var docID = $row.find('td:eq(0) input').val();
var docName = $row.find('td:eq(1)').html();
var docDescription = $row.find('td:eq(2)').text();
newRow += $('#classesTable tbody:last').append('<tr class="classDocsRow">' +
'<td></td>' +
'<td align="right"><input type="checkbox" class="chkRemoveDocs" name="removeDocs[]" value="' + docID + '-' newClassID + '" /></td>' +
'<td width="245px">' + docName + '</td>' +
'<td width="600px">' + docDescription + '</td>' +
'</tr>');
});
//$('#classesTable tbody:last').append('<tr class="classDocsRow"><td></td><td align="right"><input type="checkbox" class="chkRemoveDocs" name="removeDocs[]" value="' + docID + '-' newClassID + '" /></td><td width="245px">' + docName + '</td><td width="600px">' + docDescription + '</td></tr>');
} else {
newRow += $('#classesTable tbody:last').append('<tr class="classDocsRow">' +
'<td colspan="4">' +
'<strong>No documents are currently associated with this class.</strong>' +
'</td>' +
'</tr>');
}
return newRow;
}
Aptana Eclipse IDE is reporting an error in two places in the "if (addDocs == 'true')" section: The first error, "missing ) after argument list", is on the second line after "newRow += ..." and the second error "missing ; before statement" is two lines after that. Note that I also have that entire section in one line (not broken up with string concats) commented out shortly after that. That shows only one error, the error about missing a right paren.
If I comment out everything in the if clause and pass addDocs as false, the else clause returns a new row as expected.
This must be simply a js syntactic problem, but I can't see what I'm doing wrong.
Any help will be greatly appreciated!
You are missing the + here:
' + docID + '-' + newClassID + '" /></td>' +
^
The second error is probably just a result of the first error.

Categories