Dependent drop-down state , city , and pincode - javascript

I have a dependent drop down i.e. State -> city -> Pincode .
I am using json instead of fetching from the database .
The dropdown works fine on the local server .
But on the web-server it is relatively slow .
A part of code, is here -
for (var i = 0; i < pincodes['address'].length; i++) {
if (pincodes['address'][i]['regionname'] == city_key) {
$('#pincode').append('<option>' + pincodes['address'][i]['pincode'] + '</option>');
}
}
what are the ways , I can implement to make it load faster .

I recommend you concatenate your option HTML to a single string, so you can insert it all at once.
43,439 reasons to use append() correctly
var optionInsert = '';
for (var i = 0; i < pincodes['address'].length; i++) {
if (pincodes['address'][i]['regionname'] == city_key) {
optionInsert += '<option>' + pincodes['address'][i]['pincode'] + '</option>';
}
}
$('#pincode').append(optionInsert);

Related

Getting data from json response using Yelp API

I have a client who's using the Yelp API to get the 10 closest results to a point using a latitude and longitude. The api query combines a "list" of categories together and then passes it to the query in Yelp.
Something like this:
$categories = [ 'pharmacy', 'hospitals', 'firedepartments', 'policedepartments', 'parks', 'restaurants', 'grocery' ];
$list = join($categories, ",");
When that call is made, Yelp doesn't seem to return all the category alias' correctly. But, when each category is called individually, it does return the category alias' right.
So when I use a foreach() statement to loop the categories, like this:
foreach($categories as $k=>$v){
$resulted = yelp_search($v, $range, $lat, $lon, $num);
$resulted = json_decode($resulted, true);
$result[] = array_merge($result, $resulted);
}
It will add it to the $result array. But the problem is, that it will only add the last category to the list, for example in this case "grocery". So when the function in javascript is selected for "closest" it will only show the grocery icons on the map and in the list, not everything it returns.
That's issue #1, issue #2 is this. In the list displayed, because 'category' is being set as 'closest' to a function in javascript, I have to go through and look at the categories in the json data returned, and check if it matches something in the list.
like this
for (var i = 0; i < count; i++) {
var b = results[category]['businesses'][i];
if(category == "closest"){
ccount = b.categories.length;
for(var m = 0; m < ccount; m++){
console.log(b.categories[m]['alias']);
var alias = cats.includes(b.categories[m]['alias']);
if(alias){
var c = b.categories[m]['alias'];
break;
}
else{
var c = results[category]['category_name'];
}
}
update = update + '<tr><td role="button" class="td_menu" data-category="' + c + '" data-index="' + i + '"><img style="height: 20px; padding-right: 5px;" src="<?php echo get_template_directory_uri(); ?>/images/' + c + '.png"><span style="vertical-align: top;">' + b.name +
'</span></td><td></td><td>' + (b.distance * 0.00062137).toFixed(2) + '</td><td>mi</td></tr>\n';
}
else{
update = update + '<tr><td role="button" class="td_menu" data-category="' + category + '" data-index="' + i + '"><img style="height: 20px; padding-right: 5px;" src="<?php echo get_template_directory_uri(); ?>/images/' + category + '.png"><span style="vertical-align: top;">' + b.name +
'</span></td><td></td><td>' + (b.distance * 0.00062137).toFixed(2) + '</td><td>mi</td></tr>\n';
}
}
All of this part seems to work OK, because it does return the proper category alias (aka grocery) and the icons in the list do show. I suspect that once I can figure out how to get issue #1 resolved, issue #2 will fix itself.
I need some guidance on this please. I've spent 2 days trying to get this right and to show the proper icons in the list, as well as getting the closest data so that it does contain all the alias' in the data.
The Yelp answer contains also metadata, you cannot just concatenate them : you want to merge the businesses only :
$result = array();
foreach($categories as $k=>$v){
$resulted = yelp_search($v, $range, $lat, $lon, $num);
$resulted = json_decode($resulted, true);
if(array_key_exists('businesses', $result))
$result['businesses'] = array_merge($result['businesses'], $resulted['businesses']);
else
$result = $resulted ;
}
Note that the metadata are wrong (the total for example), maybe you need to update that too if you need it.
Yelp returns always the most specific keywords, so even with 'restaurants', you will have 'libanese' or 'pizza' and not 'restaurants'. If you need this keyword for displaying a marker, you can add it to the list if it is not already there.
Yelp API returns the distance from the location you are looking at : once you have your whole collection, you can sort your whole array per decreasing distance :
usort($result['businesses'], function ($a, $b){
return $a['distance'] - $b['distance'] ;
});
Now you have a list of businesses of different categories, with the closest always in first position, whatever its category is.

Iterate over specific CSS-id's with jQuery

I'm making an image gallery in which I want the user to be able to click on a thumbnail and get a bigger image displayed.
This is the php-code to iterate over all images in a directory on the server and display them and give them each a unique id.
echo '<div id="image' . $i . '" class="image">' . $thumbsrc . '</div>';
echo '<div id="bigimage' . $i . '" class="bigimage">' . $imagesrc . '</div>';
This works fine, I use
$(".bigimage").hide();
to hide the bigger images.
So what I could do now is this:
$("#image1").click(function() {
$("#bigimage1").show();
});
$("#bigimage1").click(function() {
$("#bigimage1").hide();
});
But I find for up to 30 pictures I can't write 30 instances of this so I wanted to loop it.
I tried
for (var i = 1; i < 30; i++) {
$('#image' + i).click(function() {
$('#bigimage' + i).show();
});
$('#bigimage' + i).click(function() {
$('#bigimage' + i).hide();
});
}
Which doesn't seem to work? Why not?
If I do
for (var i = 1; i < 10; i++) {
$('#image' + i).append('<p>test' + i + '</p>');
}
it appends paragraph's to every #image-element so looping selector's seem to work.
How would I do this?
Thanks beforehand.
That's because all of your click handlers use the same value, for understanding what happens, you can refer to this question: Javascript infamous Loop issue?
Since your elements have classes, you can use you classes instead. index method returns the index of the passed element in a collection. After getting the index, for selecting the corresponding element in another collection you can use the eq method.
var $img = $('.image');
var $bigImg = $('.bigimage').hide();
$img.on('click', function() {
var i = $img.index(this);
$bigImg.eq(i).show();
});
$bigImg.on('click', function() {
// this keyword refers to the clicked element
$(this).hide();
});

How can I append to a select drop down that lives on another page?

I'm working on creating a service that allows you to create team or user based challenges. Using HTML 5 specifications to design the page, I've run into a bit of an issue appending to a drop down list that resides in another page. The entirety of functionality lives within two pages, mainly by making AJAX calls to other pages. There's a little function that appends 2 properties of a team to a drop down list, but I can't seem to get it to work properly.
Code:
var teams = $.parseJSON(getAllTeams());
$('#multiPurpose').load('allTeams2.html #teamSelect');
for (i = 0; i < teams.length; i++) {
var team = $.parseJSON(getTeam(teams[i]));
if (team.ownerID === userID) {
$(
"<option value='" + team.teamID + "'>" + team.teamName
+ "</option>").appendTo('#teamSelection');
}
}
}
The #teamSelection is contained within the #teamSelect div. Any help would be great.
Adding a callback function within .load() will solve the problem. Basically, you're telling it to load everything within that div before running the for loop.
$('#multiPurpose').load(
'allTeams2.html #teamSelect',
function() {
for (i = 0; i < teams.length; i++) {
var team = $.parseJSON(getTeam(teams[i]));
if (team.ownerID === userID) {
$(
"<option value='" + team.teamID + "'>"
+ team.teamName + "</option>")
.appendTo('#teamSelection');
}
}
});

JavaScript selectAll\deselectAll checkboxes function doesn't work on IE8

I have a Webscript (.js file) developed for an Alfresco application. It handles a button that displays a form aimed at selecting members which have subscribed to an Alfresco space, in order to send them a mail.
All the checkboxes are generated dynamically with the subscribers names.
You can check any member you want and you also have a special checkbox that enables you to select or deselect all the members.
This specific checkbox works properly on Chrome and Firefox.
However, when you check it on Internet Explorer 8, none of the members are selected or deselected, whether they names are check or not.
Here is the code sample of the form generation and of the onClick functions triggered when you check the checkbox :
updateMembersList : function TS_updateMembersList(containerId)
{
var div = Dom.get(containerId);
div.innerHTML = "<div class=\"memberDiv\">" +
"<input type=\"checkbox\" id=\"selectDeselectAllCb\" checked=\"true\" onchange=\"YAHOO.Bubbling.fire('selectDeselectAllChanged')\" class=\"memberCb\"/>" +
"<label for=\"selectDeselectAllCb\" class=\"memberLabel\">" +
this.msg('label.selectDeselectAll') + "</label>" +
"</div>";
for (var i=0; i<this.members.length; i++)
{
var member = this.members[i];
var avatar = Alfresco.constants.URL_CONTEXT + "/components/images/no-user-photo-64.png";
if (member.authority.avatar && member.avatar != "")
{
avatar = Alfresco.constants.PROXY_URI + member.authority.avatar + "?c=force";
}
div.innerHTML += "<div class=\"memberDiv\">" +
"<input type=\"checkbox\" id=\"cb_" + member.authority.userName + "\" checked=\"true\" onchange=\"YAHOO.Bubbling.fire('selectDeselectMemberChanged')\" class=\"memberCb\"/>" +
"<label for=\"cb_" + member.authority.userName + "\" class=\"memberLabel\">" +
member.authority.firstName + " " + member.authority.lastName + "</label>" +
"</div>";
}
},
selectDeselectAllChanged: function selectDeselectAllChanged(){
var selectDeselectAllCb = Dom.get('selectDeselectAllCb');
var checked = selectDeselectAllCb.checked;
console.log("Select All");
var cbs = YAHOO.util.Selector.query("input[id^='cb_']");
for (var i=0, j=cbs.length; i<j; i++)
{
var cb = cbs[i];
cb.checked = checked;
}
},
selectDeselectMemberChanged: function selectDeselectMemberChanged(){
var selectDeselectAllCb = Dom.get('selectDeselectAllCb');
var cbs = YAHOO.util.Selector.query("input[id^='cb_']");
var firstChecked;
if (cbs[0] != null){
firstChecked = cbs[0].checked;
}
for (var i=0, j=cbs.length; i<j; i++)
{
var cb = cbs[i];
if (cb.checked === firstChecked){
continue;
}
else{
selectDeselectAllCb.checked = false;
return;
}
}
selectDeselectAllCb.checked = firstChecked;
},
At the beginning, I thought that the query wasn't supported by IE8, but it's not the case.
Such a syntax is supported by IE7 and more recent versions.
Try removing console.log("Select All"); and replace it with Alfresco.logger.debug("Sellect All");
IE doesn't like console object.
Also, run your code on jslint - if you have an invalid json there somewhere, IE stops.
Also, try running IE in developer mode - set it up to show you script errors and you'll know where it stops.
I've solved the problem. I've replaced the onchange event handler by an onclick event handler. Indeed, onchange has a random behaviour on Internet Explorer, whereas onclick works fine in most of the case.
Thanks for the help.

not styling late loading div

i have two select boxes
one of them is dynmaic one of them static
the dynamic one is loading with javascript (get and fill facebook friends) like below
function (response) {
//console.log(response);
var xxx = '<select id="friend" class="msdropdown" name="friend">';
for (i = 0; i < response.length; i++) {
xxx = xxx + '<option value"' + response[i]['uid'] + '">' + response [i] ['name'] + '</option>';
}
xxx = xxx + '</select>';
friendslist.innerHTML = xxx;
});
i give class to both of the select boxes but the dynamic one is not working i think because of lateness
how could i solve this problem?
In your case the css file is loaded since the static select is being styled so I don't think it's a timing issue. If you inspect the dynamic select box in firebug does it have the same class / styles applied to it?

Categories