Going in same javascript if condition irrespective of value of given variable - javascript

Even if the value of
isAdmin = false
The code is not going into the condition
if(!isAdmin)
As a result, I am not getting desired output.
This is how below if called in asp.net :
<span onclick="DisplayPrdWeightGrd('<%#Container.ItemIndex + 1 %>','<%# Eval("OrderId")%>','<%= Convert.ToBoolean(Utility.IsAdmin()) %>');">
function DisplayPrdWeightGrd(index, OrderId, isAdmin) {
$.ajax({
type: "POST",
url: "../handlers/DisplayOrderDetail.ashx?OrderId=" + Orderid + "&tk=" + $.now(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if ($('#tableOrderDetail_' + index + ' tr').length <= 1) {
$.each(data, function(i, v) {
setDataOnRow(index, v, i);
});
}
},
failure: function(response) {
alert("fail");
},
error: function(response) {
alert(response);
}
});
function setDataOnRow(idx, v, i) {
var totalprice;
if (v.IsGST == true) {
totalprice = parseFloat(v.TotalPrice * (1.1)).toFixed(2);
} else {
totalprice = parseFloat(v.TotalPrice).toFixed(2);
}
//debugger;
var obj = $('#tableOrderDetail_' + idx + ' tr td table:last');
if (!isAdmin) {
$('#tableOrderDetail_' + idx + ' tr:last').after('<tr>' +
'<td width="25%" >' + (i + 1) + '</td>' +
'<td width="25%" class="center">' + v.ProductName + '</td>' +
'<td width="12%" class="center">' + v.NoOfCarton + '</td>' +
'<td width="12%" class="center">' + v.ProductQuantity + '</td>' +
'<td width="12%" class="center">' + v.OriginalPrice + '</td>' +
'<td width="12%" class="center">' + v.OrderPrice + '</td>' +
'<td width="10%" class="center">' + v.IsGST + '</td>' +
'<td width="10%" class="center">' + v.Discount + '</td>' +
'<td width="12%" class="center">' + totalprice + '</td></tr>');
} else {
$('#tableOrderDetail_' + idx + ' tr:last').after('<tr>' +
'<td width="25%" >' + (i + 1) + '</td>' +
'<td width="25%" class="right">' + v.ProductName + '</td>' +
'<td width="12%" class="right">' + v.NoOfCarton + '</td>' +
'<td width="12%" class="right">' + v.ProductQuantity + '</td>' +
'<td width="12%" class="right">' + v.OriginalPrice + '</td>' +
'<td width="12%" class="right">' + v.OrderPrice + '</td>' +
'<td width="10%" class="right">' + v.IsGST + '</td>' +
'<td width="10%" class="center">' + v.Discount + '</td>' +
'<td width="12%" class="center">' + totalprice + '</td></tr>');
}
}
I tried debugger, it is always going is else condition for the value isAdmin is true or false. Stuck here.

You are setting the value of that isAdmin parameter as a string. So the check inside the "if" checks for the "truthy" value of the string, which is any non null/non empty value. So both the values 'True' and 'False' will be seen as true.
To solve this:
remove the quotes around <%= Convert.ToBoolean(Utility.IsAdmin()) %>
make sure you get true and false (lowercase!). You might need to add a .ToString().ToLowerInvariant(). Or (guessing that Utility.IsAdmin() returns a bool): <%= Utility.IsAdmin() ? "true" : "false" %>

Try
var isAdmin = Boolean(isAdmin);
then check if-else condition.
if(!isAdmin)

The isAdmin only exists inside your ajax call, thus your setDataOnRow function will not recognize it hence always go to the else

function DisplayPrdWeightGrd(index, OrderId, isAdmin) { var Admin = isAdmin.toLowerCase();
$.ajax({
type: "POST",
url: "../handlers/DisplayOrderDetail.ashx?OrderId=" + Orderid + "&tk=" + $.now(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if ($('#tableOrderDetail_' + index + ' tr').length <= 1) {
$.each(data, function(i, v) {
setDataOnRow(index, v, i);
});
}
},
failure: function(response) {
alert("fail");
},
error: function(response) {
alert(response);
}
});
function setDataOnRow(idx, v, i) {
var totalprice;
if (v.IsGST == true) {
totalprice = parseFloat(v.TotalPrice * (1.1)).toFixed(2);
} else {
totalprice = parseFloat(v.TotalPrice).toFixed(2);
}
//debugger;
var obj = $('#tableOrderDetail_' + idx + ' tr td table:last');
if (Admin === "false") {
$('#tableOrderDetail_' + idx + ' tr:last').after('<tr>' +
'<td width="25%" >' + (i + 1) + '</td>' +
'<td width="25%" class="center">' + v.ProductName + '</td>' +
'<td width="12%" class="center">' + v.NoOfCarton + '</td>' +
'<td width="12%" class="center">' + v.ProductQuantity + '</td>' +
'<td width="12%" class="center">' + v.OriginalPrice + '</td>' +
'<td width="12%" class="center">' + v.OrderPrice + '</td>' +
'<td width="10%" class="center">' + v.IsGST + '</td>' +
'<td width="10%" class="center">' + v.Discount + '</td>' +
'<td width="12%" class="center">' + totalprice + '</td></tr>');
} else {
$('#tableOrderDetail_' + idx + ' tr:last').after('<tr>' +
'<td width="25%" >' + (i + 1) + '</td>' +
'<td width="25%" class="right">' + v.ProductName + '</td>' +
'<td width="12%" class="right">' + v.NoOfCarton + '</td>' +
'<td width="12%" class="right">' + v.ProductQuantity + '</td>' +
'<td width="12%" class="right">' + v.OriginalPrice + '</td>' +
'<td width="12%" class="right">' + v.OrderPrice + '</td>' +
'<td width="10%" class="right">' + v.IsGST + '</td>' +
'<td width="10%" class="center">' + v.Discount + '</td>' +
'<td width="12%" class="center">' + totalprice + '</td></tr>');
}
}
It solved my issue using below two lines:
1. In function
function DisplayPrdWeightGrd(index, OrderId, isAdmin)
add
var Admin = isAdmin.toLowerCase();
2 In function
function setDataOnRow(idx, v, i)
add in if condition as
if(Admin==="false")
Thanks for discussion.

Related

Iterate through JSON and get image for each data key

I have this table
<table id="player_info">
<tr>
<th>Position</th>
<th>Club</th>
<th>Points</th>
<th>Matches Played</th>
<th>Wins</th>
<th>Draws</th>
<th>Losses</th>
<th>Goals For</th>
<th>Goals Against</th>
<th>Goal Difference</th>
<th>Form</th>
</tr>
</table>
And I have this function which iterates through JSON keys and creates a new table cell with each key. I would like to have the logo of each club appear next to its name in the table cell. The logo URL is stored in the JSON.
My current code
data.api.standings[0].forEach(elements => {
var tr = document.createElement('tr');
var img = new Image();
img.src = elements.logo;
tr.innerHTML = '<td>' + elements.rank + '</td>' +
'<td>' + elements.teamName + img + '</td>' +
'<td>' + elements.points + '</td>' +
'<td>' + elements.all.matchsPlayed + '</td>' +
'<td>' + elements.all.win + '</td>' +
'<td>' + elements.all.draw + '</td>' +
'<td>' + elements.all.lose + '</td>' +
'<td>' + elements.all.goalsFor + '</td>' +
'<td>' + elements.all.goalsAgainst + '</td>' +
'<td>' + elements.goalsDiff + '</td>' +
'<td>' + elements.forme + '</td>';
table.appendChild(tr);
});
However I am getting the team name and [object HTMLImageElement] and no image.
In your case you can do this instead
var img = '<img src="' + elements.logo + '" />'
instead of making an img element

How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))?

How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))?
$(document).ready(function () {
$.ajax({
url: '/api/Usuario/GetPermisosRolPorUsuario',
method: 'GET',
dataType:'JSON',
data: { NitEmpresa,NombreUsuario },
headers: {
'Authorization': 'Bearer '
+ sessionStorage.getItem("accessToken")
},
success: function (data) {
debugger
$('#tblBody').empty();
$.each(data, function (index, value) {
var row =
$('<tr>'
+'<td id="IdUsuario">'+ value.IdUsuario + '</td>'
+ '<td id="RolId">' + value.RolId + '</td>'
+ '<td id="Estado" >' + value.Estado + '</td>'
+ '<td>' + value.Rol + '</td>'
+ '<td>' + value.DescripcionRol + '</td>'
+ '<td>' + value.NombreUsuario + '</td>'
+ '<td>' + value.FullName + '</td>'
+ '<td>' + value.licenciaEmpresa + '</td>'
+ '<td>' + value.RazonSocial + '</td>'
+ '<td>' + value.NitEmpresa + '</td>'
+ '<td>' + value.Correo + '</td>'
+ '<td>' + value.Celular + '</td>'
+ '<td>' + formatDate(value.licenciaFechaExpire) + '</td>'
);
$('#tblData').append(row);
});
Thank you, I managed to access the brothers 'td', as follows:
$('tr td:nth-child(3)', '#tblData').click(function () {
returns to the father to look for his brothers
var $thisRow = $(this).closest('tr')
brothers td
IdUsuario = $('td:first', $thisRow).text();
RolId = $('td:nth-child(2)', $thisRow).text();
Estado= $('td:nth-child(3)', $thisRow).text();
//an alert to print the values
alert(IdUsuario + '-' + RolId + '-' + Estado);
});
},
error: function (jQXHR) {
toastr.error('Sistemas Infinitos Informa: '+jQXHR.responseText);
}
});
});
$.each(data, function (index, value) {
var row =
$('<tr>'
+'<td id="IdUsuario">'+ value.IdUsuario + '</td>'
+ '<td id="RolId">' + value.RolId + '</td>'
+ '<td id="Estado" >' + value.Estado + '</td>'
First, each element in the DOM should have a unique id. By repeating the same ID multiple times, I'm not sure your on('click') events will attach in all browsers and return the value you are looking for. Instead, your click event should look something like this:
$('tr', '#tblData').click(function () {
var id1 = $('td:first-child', this).text();
var id2 = $('td:nth-child(2)', this).text();
var id3 = $('td:nth-child(3)', this).text();
...
}
or if you only want to allow clicking on the first TD:
$('tr td:first-child', '#tblData').click(function () {
var $thisRow = $(this).closest('tr')
var id1 = $(this).text();
var id2 = $('td:nth-child(2)', $thisRow).text();
var id3 = $('td:nth-child(3)', $thisRow).text();
...
}

how to append value in td

I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in <td>. I also try to gave gave td an id e.g <td id="files">
here is my code:
function format(d) {
var str = d.files;
var myarr = str.split(",");
for (var i = 0; i < myarr.length; i++) {
alert(myarr[i]);
$("#files").append("<a href='/uploads/" + myarr[i] + "'>" + myarr[i] + "</a>");
}
// `d` is the original data object for the row
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr>' +
'<tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr>' +
'<tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr>' +
'<tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr>' +
'<tr>' +
'<td>Files:</td>' + '<td id="files">'
'</td>' +
'</tr>' +
'</table>';
}
I hope it will be a easy fix.any help will be highly appreciable
Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:
function format(d) {
var str = d.files;
var filesHtml = str.split(",").map(function(file) {
return '' + file + '';
});
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr><tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr><tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr><tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr><tr>' +
'<td>Files:</td>' +
'<td id="files">' + filesHtml + '</td>' +
'</tr>' +
'</table>';
}
var html = format({
person: 'John Smith',
phone: '1234 567890',
web: 'http://google.com',
ttype: 'Foobar',
files: 'a.jpg,b.jpg'
});
$('div').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Make dropdown item selected true dynamically

I am making dropdown item selected true dynamically using below lines of code
for(var i in data) {
var book_id = data[i]['book_id'];
var indivudvalbookdetails = data[i]['indivudvalbookdetails'];
var id=1;
for(var j in indivudvalbookdetails) {
if(indivudvalbookdetails[j]['status'] == undefined || indivudvalbookdetails[j]['status'] == "")
{
$('.library_info_tbl tbody').append('<tr>' +
'<td class="text-center centeralign"> ' + data[i]['subject'] + '</td>' +
'<td class="text-center centeralign"> ' + data[i]['title'] + ' </td>' +
'<td class="text-center centeralign"> ' + data[i]['isbn'] + '</td>' +
'<td class="text-center centeralign"> ' + data[i]['author'] + ' </td>' +
'<td class="text-center centeralign"> ' + indivudvalbookdetails[j]['acquisitionno'] + '</td>' +
'<td class="text-center centeralign"><div class="btn-group">' +
'<input type="text" class="hide" id="acquisitionno' + id + '" value="' + indivudvalbookdetails[j]['acquisitionno'] + '" class="form-control">' +
'<select id="status' + id + '" class="form-control">' +
'<option value="Select">Select</option>'+
'<option value="Damaged"' +
indivudvalbookdetails[j]['status'] == "Damaged" ? 'selected="true"': 'selected="false">Damaged</option>'+
'<option value="Lost"' +
indivudvalbookdetails[j]['status'] == "Lost" ? 'selected="true"' : ' selected="false">Lost</option>' +
'</select>'+
//'<input type="text" id="status' + id + '" class="form-control">' +
'</div></td>' +
'</tr>');
id++;
}
}
It is displaying the code in html like:
"selected="false">Lost selected="false">Lost
selected="false">Lost selected="false">Lost selected="false">Lost"
The string termination is not right and the if condition as well.
Check the code below:
var id = 'select';
var indivudvalbookdetails = [{
status: 'Damaged'
}]
var j = 0;
var select = '<select id="status' + id + '" class="form-control">' +
'<option value="Select">Select</option>' +
'<option value="Damaged"' +
(indivudvalbookdetails[j]['status'] == "Damaged" ? 'selected="selected"' : '') + '>Damaged</option>' +
'<option value="Lost"' +
(indivudvalbookdetails[j]['status'] == "Lost" ? 'selected="selected"' : '') + '>Lost</option>' +
'</select>'
document.getElementById('main').innerHTML = select;
<div id="main"></div>

Vue.js orderBy TotalPrice and Rate asc

Im trying to set the vue.js to orderBy a table of search result items, by TotalPrice or Rate. (clickable column header).
I tried vue.js documentatiom but the ascending ordering is not working.
My code:
var SearchResultComponent = Vue.extend({
template:
'<div class="table-responsive">' +
'<h3 class="selectedItemsHeader" style="margin-top:0;margin-bottom:0;">{{ language.resultsItems }}</h3>' +
'<table class="table">' +
'<thead>' +
'<tr>' +
'<th style="width:15%">' +
'{{ language.company }} <i class="fa fa-caret-down"></i>' +
'</th>' +
'<th style="width:30%">{{ language.service }}</th>' +
'<th style="width:10%">{{ language.servicePrice }}</th>' +
'<th style="width:10%">{{ language.discount }}</th>' +
'<th style="width:15%">{{ language.info }}</th>' +
'<th style="width:10%">' +
'{{ language.totalVat }} <i class="fa fa-caret-up"></i>' +
'</th>' +
'<th></th>' +
'</tr>' +
'</thead>' +
'<tbody v-if="items.length > 0">' +
'<tr v-for="item in items | orderBy itemByTotalPrice">' +
'<td class="clearfix">{{ item.companyName }}'+
'<span class="rate" v-if="item.companyRate"><span class="star"></span><span class="point">{{ item.companyRate }} / 5</span></span>'+
'</td>' +
'<td class="small-text item-name">{{{ getItemName(item) }}}</td>' +
'<td>{{ totalPriceNoDiscount(item) }} €</td>' +
'<td>{{ totalPriceDiscount(item) }} €</td>' +
'<td class="small-text">{{ item.companyNote || \' - \' }}</td>' +
'<td>{{ totalPrice(item) }} €</td>' +
'<td>'+
'<button class="btn btn-primary btn-sm" #click="select(item, $event)">{{ language.select }}</button>' +
'</td>' +
'</tr>' +
'</tbody>' +
'<tbody v-if="items.length == 0">' +
'<tr>' +
'<td colspan="7" style="font-size: 12pt;color: #777;padding-top: 60px;">{{ language.noResultsFound }}</td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'<h3 class="selectedItemsHeader" v-if="selectedItems.length > 0">{{ language.selectedItems }}</h3>' +
'<table class="table selectedItems" v-if="selectedItems.length > 0">' +
'<tbody>' +
'<tr v-for="item in selectedItems">' +
'<td style="width:15%">{{ item.selectedItem.companyName }}' +
'</td>' +
'<td style="width:30%" class="small-text item-name">{{{ getItemName(item.selectedItem) }}}</td>' +
'<td style="width:10%">{{ totalPriceNoDiscount(item.selectedItem) }} €</td>' +
'<td style="width:10%">{{ totalPriceDiscount(item.selectedItem) || \'0.00\' }} €</td>' +
'<td style="width:15%" class="small-text">{{ item.selectedItem.companyNote || \' - \' }}</td>' +
'<td style="width:10%">{{ totalPrice(item.selectedItem) }} €</td>' +
'<td>'+
'<button class="btn btn-danger btn-sm" #click="remove(item)"><i class="fa fa-remove"></i></button>' +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>',
props: ['items','selectedItems','removeUrl'],
data: function(){ return { sortBy: 'total' } },
computed: {
'language' : function() { return language; }
},
methods: {
'select' : function(item, ev) {
this.$dispatch('onCompanySelect', item);
$(ev.target).attr('disabled', true).addClass('disabled');
},
'remove' : function(item) {
this.$dispatch('onSelectedItemRemove', {
removeUrl: this.removeUrl,
item: item
});
},
'totalPriceNoDiscount' : function(item) {
return item.priceNoDiscount.toFixed(2);
},
'totalPriceDiscount' : function(item) {
return (item.priceNoDiscount - this.totalPrice(item)).toFixed(2);
},
'totalPrice' : function(item) {
return item.extraServicesPriceVat ? (item.priceVat + item.extraServicesPriceVat).toFixed(2) : item.priceVat.toFixed(2);
},
'itemByTotalPrice' : function(a, b) {
if(this.sortBy == 'total') {
$('a.companyrate').css('color', '#333');
$('a.totalVat').css('color', '#337ab7');
return this.totalPrice(a) > this.totalPrice(b);
} else if(this.sortBy == 'rate') {
$('a.totalVat').css('color', '#333');
$('a.companyrate').css('color', '#337ab7');
return a.companyRate < b.companyRate;
}
}
}
});
Any suggestions ? Thank you in advance

Categories

Resources