Javascript get value from multi dimensional array - javascript

I experience an issue with getting values from an array. For some reason I can't get it to work (just getting [object]) and appreciate any help here:
Here I'm creating the response
foreach ($locations as $location) {
if($location->getStreet1() != ''){
$result .= $location->getStreet1() .', ';
}
if($location->getCity() != ''){
$result .= $location->getCity() .', ';
}
$locationList[$i]['location'] = addslashes(htmlspecialchars($location->getName()));
$locationList[$i]['address'] = addslashes(htmlspecialchars($result));
$i++;
$result = '';
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode(array('locations' => $locationList)));
And here I'm handling the response:
request.done(function(data) {
var container = jQuery('#hotel-list-container');
var locations = jQuery.parseJSON(data).locations;
container.html('');
var firstSymbols = [];
locations.forEach(function(location) {
var firstSymbol = location.location;
if (jQuery.inArray(firstSymbol, firstSymbols) === -1) {
firstSymbols.push(firstSymbol);
}
});
firstSymbols.forEach(function(firstSymbol) {
if (jQuery.isNumeric(firstSymbol)) {
if (container.find('.numeric').size() === 0) {
container.append('<div class="numeric">0–9</div>');
}
} else {
container.append('<div class="letter">' + firstSymbol + '</div>');
}
locations.forEach(function(data) {
if (firstSymbol == data.location) {
container.append('<div class="hotel-item"><a class="hotel" data-id="' + data.location + '"><div class="hotel_addr_div"><span>' + data.location +'</span>'+data.address+'</div></a></div>');
console.log(data.location);
}
});
});
container.slideDown(null, function() {
jQuery('#hotel-list-container').mCustomScrollbar({ scrollInertia: 0 });
});
});
locations.forEach(function(data) {
if (firstSymbol == data.location) {
container.append('<div class="hotel-item">
<a class="hotel" data-id="' + data.location + '">
<div class="hotel_div"><span>' + data.location +'</span>'+data.address+'</div>
</a>
</div>');
}
And that is what I'm seeing in frontend
<div class="hotel-lists" id="hotel-list-container-mobile" style="max-height: 497px;">
<div class="letter">undefined</div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
</div>
Thanks for all answers. Like requested I added the full code in here

Related

How to make a dropdown show values from top instead of where I left it?

On my web form application, I have shown a dashboard with six boxes each with a separate dropdown showing values from a database table. This is for my user's ease of accessibility as they will choose approximately six menu items which they visit most frequently. The dropdown is working fine and show the selected menu items appropriately.
However, the problem is that none of the dropdown show values afresh as it must be. Because once a value is selected from it or just the mouse is scrolled down on it without making any selection, it remember that position. Now when that first dropdwon is revisited again either after selecting a value from another dropdown or just scrolling down the mouse on that another dropdown, the position of the first dropdown remain exactly where it was left before.
I want each and every dropdown to show values from its top and not where user left it before. The code is available here.
//
//
//Menu items are taken from database
if (obj.data.length > 0) {
var lielm = '';
var AccountantHeader = false;
var ReportHeader = false;
var OtherHeader = false;
var accountantItems = [];
var reportsItems = [];
var otherItems = [];
$.each(obj.data, function (i, m) {
if (m.Menu_Item_Name == 'Report Financial' || m.Menu_Item_Name == 'Cover Sheet' || m.Menu_Item_Name == 'Letters' || m.Menu_Item_Name == 'Invites')
{
accountantsItems.push(m);
}
else if (m.Menu_Item_Name == 'Income Statement' || m.Menu_Item_Name == 'Balance' || m.Menu_Item_Name == 'Income' || m.Menu_Item_Name == 'Ledger')
{
reportsItems.push(m);
}
else
{
otherItems.push(m);
}
});
$.each(accountantItems, function (index, m) {
if (!AccountantHeader) {
lielm += '<li class="no-hover"><strong>Accountants</strong></li>';
AccountantHeader = true;
}
lielm += '<li data-value="' + m.Menu_URL + '" title="' + m.Menu_Item_Name.replace('<strong>', '').replace('</strong>', '') + '">' + m.Menu_Item_Name + '</li>';
});
$.each(reportsItems, function (index, m) {
if (!ReportHeader) {
lielm += '<li class="no-hover"><strong>Reports</strong></li>';
ReportHeader = true;
}
lielm += '<li data-value="' + m.Menu_URL + '" title="' + m.Menu_Item_Name.replace('<strong>', '').replace('</strong>', '') + '">' + m.Menu_Item_Name + '</li>';
});
$.each(otherItems, function (index, m) {
if (!OtherHeader) {
lielm += '<li class="no-hover"><strong>Other</strong></li>';
OtherHeader = true;
}
lielm += '<li data-value="' + m.Menu_URL + '" title="' + m.Menu_Item_Name.replace('<strong>', '').replace('</strong>', '') + '">' + m.Menu_Item_Name + '</li>';
});
$(edt).next('.dropdownContain').children('.dropOut').children('.widget-options').html(lielm);
$(edt).next('.dropdownContain').children('.dropOut').children('.widget-options').children('li').click(function () {
var pId = $(edt).parent().parent().attr('id');
var mId = $('#' + pId + ' .menu-id').val() || 0;
var mnu = { UserId: uId, Name: this.outerText, Url: $(this).data('value'), ID: mId }
//
//
// Update dashboard
Here is the HTML belong to just a single box (one out of the six sections I have made for dropdowns)
<div class="row">
<div class="box" id="box0">
<div class="drop">
<div class="edit"><span><i class="fa fa-pencil fa-lg"></i></span></div>
<div class="dropdownContain">
<div class="dropOut">
<div class="triangle"></div>
<ul class="widget-options">
</ul>
</div>
</div>
</div>
<a class="menu-href" href="javascript:">
<input type="hidden" class="menu-id" />
<span class="menu-icon fa fa-2x"> </span>
<div class="clearfx"></div>
<label class="menu-text"> </label>
</a>
</div>
Any help in this regard will highly be appreciated.

Class added behind targeted element

I have a forloop which appends a div with child elements for each item
for (i = 0; i < len; ++i) {
if (i in courseModuleList) {
s = courseModuleList[i];
if (this.modules.get(s) != undefined) {
var moduleName = (this.modules.get(s).get('Id'));
var moduleId = (this.modules.get(s).get('OptimeIndex'));
var courseDuration = (courseTemplate.get('Duration'));
var scheduleClass;
var scheduleStatus;
var startDate;
if (scheduleStatus === "Fully Scheduled") {
scheduleClass = "cpCreatedCourseStatusScheduled";
} else if (scheduleStatus === "Part Scheduled") {
scheduleClass = "cpCreatedCourseStatusPartScheduled";
} else if (scheduleStatus === "Unscheduled") {
scheduleClass = "cpCreatedCourseStatusUnscheduled";
} else {
scheduleClass = "cpCreatedCourseStatusUnscheduled";
}
if (courseDuration == 1) {
courseDuration += " day";
} else {
courseDuration += " days";
}
div.append('<div id="selectedCourse" data-id=' + moduleId + '> <a href="#" class="list-group-item cpCreatedCourseWrap clearfix">' +
'<div class="col-lg-6 col-md-12">' +
'<div id="courseName" class="cpCreatedCourseName">' + moduleName + '</div>' +
'<div class="cpCreatedCourseDuration">' + courseDuration + '</div>' +
'</div>' +
'<div class="col-lg-3 col-md-6 col-sm-6 col-xs-6 cpCreatedCourseStatusWrap">' +
'<label>Schedule Status:</label>' +
'<div class="' + scheduleClass + '">' + scheduleStatus + '</div>' +
'</div>' +
'<div class="col-lg-3 col-md-6 col-sm-6 col-xs-6 cpCreatedCourseDateWrap">' +
'<label>Start Date:</label>' +
'<div class="cpCreatedCourseDate">' + startDate + '</div>' +
'</div>' +
'</a> </div>');
}
}
}
I then added a click event on '#selectedCourse' to add a class to the selectedCourse div if the data-id equals a item in an array.
this.$el.find('#selectedCourse').removeClass('cpCreatedCourseWrapActive');
var stepType = $(e.currentTarget).data('id');
var steps = [];
var i, s, courseModuleList = (this.courseTemplate.get('ModuleIndexList')),
len = courseModuleList.length;
for (i = 0; i < len; ++i) {
if (i in courseModuleList) {
s = courseModuleList[i];
if (this.modules.get(s) != undefined) {
var optimeIndex = (this.modules.get(s).get('OptimeIndex'));
steps.push(optimeIndex);
}
}
}
_.each(steps,
function(step) {
if (stepType === step) {
$(e.currentTarget).addClass('cpCreatedCourseWrapActive');
}
});
this is my css
.cpCreatedCourseWrapActive:hover{
background-color:#ddd;
}
.cpCreatedCourseWrapActive{
background-color:#ddd !important;
}
When I click on an element it seems to add behind the element as I can see the colour around the edges. In the image below I changed the background-color to blue to make it clear
Any ideas where I have went wrong? Any help would be appreciated.

Getting JSON Object then adding parts to HTML

I have been trying to get a script to work for my Github site and I am processing a JSON file to get an array to HTML in a ordered list.
My code I have been using is:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(mods, function(i) {
var tempUrl = "";
var tempApproved = "";
if (data.mods[i].Repo[0] == 0) {
tempUrl = data.mods[i].Repo[1];
} else if (data.mods[i].Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + data.mods[i].Repo[1] + "/";
} else {
tempUrl = data.mods[i].Repo[1];
}
if (data.mods[i].Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + data.mods[i].Title + "</a> - by " + data.mods[i].Author + "<ul><li>\t- <input type='checkbox' " + tempApproved + "/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
So what have I been doing wrong because nothing is working...
This should work:
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
$.each(data.mods, function(i, m) {
var tempUrl = "";
var tempApproved = "";
if (m.Repo[0] == 0) {
tempUrl = m.Repo[1];
} else if (m.Repo[0] == 1) {
tempUrl = "http://community.playstarbound.com/resources/" + m.Repo[1] + "/";
} else {
tempUrl = m.Repo[1];
}
if (m.Approved == true) {
tempApproved = "checked";
} else {
tempApproved = "";
}
$("#modsList").append("<li><a href='" + tempUrl + "'>" + m.Title + "</a> - by " + m.Author + "<ul style='list-style-type:none'><li>\t - <input type='checkbox' " + tempApproved + " disabled/> Approved</li></ul></li>");
});
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>
Instead of $.each(mods, function(i) { it should be $.each(data.mods, function(i, m) {. and the mods[i]. should be m..
Also there was a formatting error in the JSON file but now it is fixed. It was causing the errors to not display.

Dynamically binding panel in jquery mobile

I am dynamically adding data to the panel in jquery mobile however on loading the page the first time the panel doesn't work however if i refresh it it starts working properly.
var prof = '';
var panel = '';
$(document).one('pagecreate', '[data-role="page"]', function () {
if (sessionStorage.getItem('sessionid') !== '' || sessionStorage.getItem('sessionid') !== null && sessionStorage.getItem('user_id') !== '' || sessionStorage.getItem('user_id') !== null) {
var jxhr = $.post(getdetails + '' + 'Users', {
session_id: sessionStorage.sessionid,
id: sessionStorage.getItem('user_id')
}, function (data) {
var ourhtml = getRecordDetailProfileCheck(data);
prof = "<div style='text-align:center;'>" + ourhtml + "</div><div></div>";
sessionStorage.setItem('prof', prof);
panel = '<div data-role="panel" data-theme="b" data-display="push" id="mypanel"><ul data-role="listview" data-role="none" class="ulpanel"><br/><div id="panelimage"></div>' + prof + '<div><br/></div><li><i class="lIcon main"></i>MAIN SERVICE</li><li><i class="lIcon main"></i>SPECIAL EVENTS</li><li><i class="lIcon main"></i>LIFE GROUPS</li><li><i class="lIcon main"></i>SUNDAY SCHOOL</li><li><i class="lIcon main"></i>PRAYER & PRAISE</li><li><i class="lIcon main"></i>FACTORY & YOUTH MIX</li><li><i class="lIcon main"></i>VOLUNTEER</li></ul></div>';
$.mobile.pageContainer.prepend(panel);
$("#mypanel").panel().enhanceWithin();
var img = '';
var va = getRecordIdPicture(data);
if (va !== '') {
img = file + "?session_id=" + sessionStorage.getItem('sessionid') + "&id=" + va;
} else {
img = 'images/man.png';
}
$("#mypanel #panelimage").attr('style', 'margin: 0 auto;text-align:center;width: 128px;height: 128px;border-style: solid;-webkit-border-radius: 100px;-moz-border-radius: 100px;background: url(' + img + ') no-repeat 100% 100%');
// console.log(data);
});
} else {
for (var i = 0; i < sessionStorage.length; i++) {
var key = sessionStorage.key(i);
if (/foo/.test(key)) {
sessionStorage.removeItem(key);
}
}
$.mobile.changePage("#one", {
transition: "slide",
reverse: false,
changeHash: true
});
}
});
Calling the panel:
<div data-role="header" data-position="fixed" data-tap-toggle="false" data-theme='b'>
<a href='#mypanel' data-role='button' data-iconpos='left' data-inline='true'><i class='fa fa-bars'></i></a>
<h1 style="text-align: center;"><img src="images/pcc.png" height="26"/></h1>
<i class='fa fa-power-off'></i>
</div>
I have tried everything i somehow feel the session is not being set? Please could someone help
Thanks

undefined error when iterating over json list

i got this code that keep on returning undefined msg instead of the expected html.
Purpose of function:
the purpose of the below function is to return notifications in away similar to fb one's. the code is working fine. but there's something wrong with the getJSON part that i couldn't figure out. so instead of returning "clonex1 likes your post" i get undefined.
the code
function buzzme()
{
jQuery('#cnumber').removeClass();
jQuery('#cnumber').empty();
jQuery('#floating_box').toggle();
var nHeader = '<div id="floating_box" class="fb">' +
'<div id="header"><span id="htext">Notifications</span></div>' +
'<div id="int">' +
'<div id="bodyx">' +
'<ul>';
var nFooter = '</ul>' +
'<div class="jfooter">' +
'See all notifications' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var nContent;
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
});
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
}
notifications.php - setUpFlayout(); and setUpJSONList()
function setUpFlyout() {
$notify = new se_notify();
$data2 = $notify->notify_summary();
$trk = 0;
if($data2['total'] >= 1) {
for($i = 0; $ $i <= $data2['total']; $i++) {
$nid = $data2['notifys'][$i]['notify_id'];
$im = $data2['notifys'][$i]['notify_icon'];
$img = "<img src='./images/icons/$im' />";
$notifier = $data2['notifys'][$i]['notify_text'][0];
$atype = $data2['notifys'][$i]['notifytype_id'];
$url = '';
$url2 = $data2['notifys'][$i]['notify_url'];
if($atype == 1) {
$url = ' has sent you friend <a href='.$url2.'>request</a>';
}
$trk++;
if($data2['total'] >= 2) {
$ret_arr = '';
if($i == 0) {
$ret_arr = '[';
}
$ret_arr = $ret_arr.setUpJSONList($data2['total'], $nid, $img, $notifier, $url, $trk);
if($i == $data2['total']-1) {
$ret_arr = $ret_arr.']';
}
echo '';
} else if($data2['total'] == 1){
//$ret_arr = '[{"dh3":"'.$data2['total'].'","nid":"'.$nid.'", "img":"'.$img.'","notifier":"'.$notifier.'","url":"'.$url.'"}]';
$ret_arr = '';
echo $ret_arr;
}
if($i == ($data2['total']-1))
break;
}
}
}
setUpJSONList();
function setUpJSONList($total, $nid, $img, $notifier, $url, $track) {
$comma = ',';
$lp = '';
$rp = ']';
$result = '';
if($track == $total) {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"}';
} else {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"},';
}
return $result;
}
thanks
Your usage of nContent after getJSON might be undefined since getJSON is asynchronous and would not have completed initializing nContent. You need to move the code using nContent inside the callback of getJSON.
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
});

Categories