Below is the JS (jQuery) code of autocomplete's result function. You can see there's some lines where I print out <li>s containing some data properties (that come in as a result of automcomplete's AJAX call).
How could I rewrite this so that <li> would be conditionally rendered based on whether the property contains any value being either int or string (not empty string or whitespace) or something else that can be represented as string?
$(".clients-dropdown").result(function (event, data, formatted) {
if (data) {
// set the hidden input that we need for Client entity rematerialize
$(".client-id").val(data.client_id);
if (data.ClientName && data.Address1 && data.postalcode && data.postname) {
$(".client-address").html(
"<li>" + data.ClientName + "</li>" +
"<li>" + data.Address1 + "</li>" +
"<li>" + data.postalcode + " " + data.postname + "</li>"
);
$(".client-details").html(
"<li>" + data.PrettyId + "</li>" +
"<li>" + data.VatNo + "</li>" +
"<li>" + data.Phone + "</li>" +
"<li>" + data.Mobile + "</li>" +
"<li>" + data.Email1 + "</li>" +
"<li>" + data.Contact + "</li>"
);
}
}
Also, for the AJAX call, should my server side action return null when there's a null for a property in the database or empty string?
Note sure if that's what you want.
$(".clients-dropdown").result(function (event, data, formatted) {
var new_li = function(data) {
$.trim(data) != "" ? "<li>" + data + "</li>" : ''
}
if (data) {
$(".client-id").val(data.client_id);
if (data.ClientName && data.Address1 && data.postalcode && data.postname) {
$(".client-address").html(
new_li(data.clientName) +
new_li(Address1) + ... // you get the idea
);
}
}
Make a function that will test the property for whitespace.
var getListItem = function(prop){
if(!!$.trim(prop))
return '<li>' + prop + '</li>';
return '';
};
$(".clients-dropdown").result(function (event, data, formatted) {
if (data) {
// set the hidden input that we need for Client entity rematerialize
$(".client-id").val(data.client_id);
if (data.ClientName && data.Address1 && data.postalcode && data.postname) {
$(".client-address").html(
getListItem(data.ClientName) +
getListItem(data.Address1) +
getListItem(data.postalcode + ' ' data.postname)
);
$(".client-details").html(
getListItem(data.PrettyId) +
getListItem(data.VatNo) +
getListItem(data.Phone) +
getListItem(data.Mobile) +
getListItem(data.Email1) +
getListItem(data.Contact)
);
}
}
Related
here is my table snap enter image description here
I am creating this table from my model in razor view
it shows the structure of task and sub-tasks and their subtask ...
but the problem is it loads sub task and their subtask ... in the same level when someone clicks on the first column it loads its child under the parent
it's loads them and add a table row under the correspondence row
here is my jquery code I want to make it hierarchical like there should be a difference in parent and child level
function showHierarchy(taskId) {
if ($('.subtaskof_' + taskId).text() == '') {
$.ajax('/Tasks/sfsubtasks?taskId=' + taskId, // request url
{
async: false,
success: function (data, status, xhr) {// success callback function
var subtasklist = JSON.parse(data)
console.log(subtasklist);
for (i = 0; i < subtasklist.length; i++) {
subtask = subtasklist[i];
var therowis = '<tr class=subtaskof_' + taskId + '>'
+ '<td id="subtaskrow_' + subtask['InstanceId'] + '" align="right">_</td>'
+ '<td>' + subtask['InstanceId'] + '</td>'
+ '<td>' + subtask["Title"] + '</td>'
+ '<td>' + subtask["Deliverables"] + '</td>'
+ '<td>' + subtask["StartDate"] + '</td>'
+ '<td>' + subtask["Priority"] + '</td>'
+ '<td>' + subtask["State"] + '</td>'
+ '<td>See Details_subt</td>'
+ '<td>Add Sub Task_subt</td>'
+ '</tr>'
// Find position to add new subtask row in the Task table
$("#my-grid tr").filter(function () {
if ($(this).text().indexOf(taskId) >= 0) {
$(this).after(therowis);
issubsubtaskexists = false;
console.log("chield checking for - " + subtask['InstanceId'])
$.ajax('/Tasks/sfsubtasks?taskId=' + subtask['InstanceId'], // request url
{
async: false,
success: function (data_, status_, xhr_) {
if (data_.length > 0) {
console.log("The data_ is - " + data_);
var subsubtasklist = JSON.parse(data_);
console.log("The subsubtasklist is - " + subsubtasklist)
console.log("lenght for - " + subtask['InstanceId'] + " , is - " + subsubtasklist);
if (subsubtasklist.length > 0) {
$('#subtaskrow_' + subtask['InstanceId']).html("<b><a style='font-size:25px; padding-left:17px;' id='lnk_" + subtask['InstanceId'] + "' href='#' onclick='showHierarchy(" + subtask['InstanceId'] + ")'> + </a></b>")
issubsubtaskexists = true;
}
}
}
});
console.log("The taskId is - "+taskId)
$('#lnk_' + taskId).html('<b>_</b>');
}
});
}
}
});
} else {
// Toggle/removing subtasks
$('.subtaskof_' + taskId).remove();
$.ajax('/Tasks/sfsubtasks?taskId=' + taskId,
{
success: function (data, status, xhr) {
console.log("Checking for child node of taskId - " + taskId);
var subsubtasklist = JSON.parse(data)
console.log(subsubtasklist);
for (i = 0; i < subsubtasklist.length; i++) {
$('.subtaskof_' + subsubtasklist[i]['InstanceId']).remove();
$.ajax('/Tasks/sfsubtasks?taskId=' + subsubtasklist[i],
{
success: function (data, status, xhr) {
console.log("Checking for child node of taskId - " + taskId);
var subsubtasklist_ = JSON.parse(data)
console.log(subsubtasklist_);
for (j = 0; j < subsubtasklist_.length; j++) {
$('.subtaskof_' + subsubtasklist_[j]['InstanceId']).remove();
}
}
});
}
}
});
$('#lnk_' + taskId).html('<b>+</b>');
}
}
plz let me know what can be done of this table for showing data hierarchically
I have an array of objects, that I loop through using $.each and try and append the array object value to an <li>.
Please find the jQuery below
$(".sidebar").empty().append("<div>"+
"<h5>Student Info</h5>" +
"<ul>" +
$.each(studentInfo, function (index, value) {
console.log(value.studentName + " :studentName ");//prints the student name in the browser console
"<li>Student No " + index + "</li>"
"<li>Name - " + value.studentName + "</li>"
"<li>Contact - " + value.contact + "</li>"
"<li>DOB - " + value.dob + "</li>"
"<li>PAN - " + value.PANNo + "</li>"
"<li>Address - " + value.postalAddress + "</li>"
}) +
"</ul>" +
"</div>")
The above function only prints [object Object],[object Object] in the <li>. I have tried stringifying the array, parsing the array, different ways of appending json objects but its still the same.
The array of objects that I am trying to loop through
var studentInfo = [
{
"studentName":"abc",
"contact":"123456789",
"dob":"22-05-1994",
"PANNo":"ABCDEF1234",
"postalAddress":"chandigarh, sector - 18"
},
{
"studentName":"xyz",
"contact":"123456987",
"dob":"22-05-1994",
"PANNo":"ABCDEF4321",
"postalAddress":"chandigarh, sector - 78"
}
]
I have been at it for hours but unable to figure out what I am doing wrong, I am still new at jQuery and its ways. Any help is really appreciated. Thanks.
jQuery $.each() is not meant to return a string. you use it to treat each object separately. You can't just parse it as string expression.
You will need to split your code into multiple parts.
Part 1: clear .sidebar and prep it for the menu items.
Part 2: build a string items that contain all the object values parsed into HTML list-items.
Part 3: append the string to the '.sidebar'
var studentInfo = [
{
"studentName":"abc",
"contact":"123456789",
"dob":"22-05-1994",
"PANNo":"ABCDEF1234",
"postalAddress":"chandigarh, sector - 18"
},
{
"studentName":"xyz",
"contact":"123456987",
"dob":"22-05-1994",
"PANNo":"ABCDEF4321",
"postalAddress":"chandigarh, sector - 78"
}
];
var items = "";
$.each(studentInfo, function (index, value) {
console.log(value.studentName + " :studentName ");
items += "<li>Student No " + index + "</li>"
+ "<li>Name - " + value.studentName + "</li>"
+ "<li>Contact - " + value.contact + "</li>"
+ "<li>DOB - " + value.dob + "</li>"
+ "<li>PAN - " + value.PANNo + "</li>"
+ "<li>Address - " + value.postalAddress + "</li>"
+ "<hr>" ;
})
+
$(".sidebar").empty().append("<div>"+
"<h5>Student Info</h5>" +
"<ul>" + items + "</ul></div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="sidebar"></div>
I am trying to add an if statement to check if a particular property exist in JSON file, to write the value, if not, do nothing.
I want that property if exist to be written in HTML between <div class='titleHolder'> and "<div class='posterHolder'>"
Between these two divs i want to have property X, only if exist in JSON file
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id=' + data[ i ].id + '" + <div class="itemsHolder">' +
"<div class='titleHolder'>" +
"<h2 >" + data[ i ].name + "</h2>" +
"</div>"+
"<div class='posterHolder'>" + data[ i ].posterPath + "</div>" +
"<div class='summaryShort'>" + data[ i ].summary + "</div>" +
"<div class='raiting'><p>" + data[ i ].imdb + "</p></div><div class='genderMovie'> " + data[ i ].gender + "</div> " +
"<div class='directorNdScreen'>" + 'Director by ' + " <p class='director'>" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class='screenplay'>" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>")
}
} )
} );
Break your append part in variables and then concate it. may be that can help ?
$(document).ready(function() {
$.getJSON( "js/appjson.json", function(data) {
for (var i = 0; i < data.length; i++) {
var content_append = "normal content";
if(data[i])
{
content_append = "content here with data[i]"
}
$('#jsonLoad').append(content_append);
}
});
});
'<div>' +
(something === something_else)? 'some data1' : 'some data2' +
'</div>'
Hi Im populating select > options using my json using below code. Here my doubt is I want to add custom attribute only if value is "IN". Anyone can help to achieve this
$.each( data, function( i, val ) {
items.push( "<option value='" + val.countryCode + "'>" + val.countryName + "</option>" );
});
Try something like this
$.each( data, function( i, val ) {
items.push( "<option value='" + val.countryCode +( val.countryCode == "IN" ? "data-attr = 'value'" : "" ;) "'>" + val.countryName + "</option>" );
});
Currently it's only possible with a if condition. You can increase speed by breaking on the first found result, but you need to use a for-loop:
for(var i=0;i<countryArr.length;i++) {
if(countryArr[i].countryCode === "IN") {
items.push( "<option value='" + countryArr[i].countryCode + "'>" + countryArr[i].countryName + "</option>" );
break;
}
});
If you want to use forEach see this post.. But a some expression might be easier:
countryArr.some(function(data) {
var check=countryArr[i].countryCode ==="IN";
if(check) {
items.push("<option value='" + data.countryCode + "'>" + data.countryName + "</option>");
}
return check; //some stops, if it returns true
});
ECMA6 will introduce a find method so you can shortcut this:
items.push(countryArr.find(function(data) {
return data.countryCode === "IN";
});
$.each( data, function( i, val ) {
if(val.countryCode !='IN') {
items.push( "<option value='" + val.countryCode + "'>" + val.countryName + "</option>" );
}
else {
items.push( "<option data-id=1 value='" + val.countryCode + "'>" + val.countryName + "</option>" );
}
});
If I understand your question correctly:
$.each( data, function( i, val ) {
items.push( "<option "+ (val.countryCode === "IN" && "data-id=1" || "") + " value='" + val.countryCode + "'>" + val.countryName + "</option>" );
});`
I have some simple code. The problem im facing is that how you can see the code is not very clean because in every line where a string gets added to var text i would like to check if the data i want to add really is defined. Now i would like to know how i can write this more cleaner? Thanks
var text = '<br><address><strong>' + data.vorname + ' ' + data.name + '</strong><br>';
if(data.strasse != null && data.strasse != ''){
text += data.strasse + '<br>' + data.plz + ', ' + data.wohnort ;
}if(data.telefon != null && data.telefon != ''){
text += '<br><strong>Tel: ' + data.telefon + '</strong>';
}
text += '<br><strong>Handy: ' + data.handy + '</strong><br>';
text += '<a href="mailto:#">' + data.mail;
text += '</a></address><address><strong>GEB: </strong>';
text += Data.datum(data.geburtsdatum) + '<br>';
text += data.gewicht + '<strong> GK';
........
You could rewrite your lines like this:
text += (data.handy)? '<br><strong>Handy: ' + data.handy + '</strong><br>' : '';
This is shorthand for this:
if (data.handy) {
text += '<br><strong>Handy: ' + data.handy + '</strong><br>';
} else {
text += '';
}
That way, if data.handy isn't defined or is null then nothing gets added to text.