jQuery Select Option from Json

jQuery select option population using json as data source

jQuery select option tutorial will show how you can glue together the following terms together

  • select box
  • JSON
  • jQuery
  • *Javascript

* You might ask isn’t jQuery javascript? Yes indeed you are right, but jQuery is a framework making javascript programming a lot easier.

When I say plain javascript, or as some are calling it old school javascript, I meant to use the same task without using jQuery.

What select box is and types of select box options

Select box is one of the most used HTML element along with text input, radio option and the like.

Select box will allow you to provide dropdown options where you can select one or more items from it. You can make the select box to allow multiple selection using multiple attribute


Continue reading jQuery Select Option from Json

Browser shows the same image after the update

If there is an image change on the same file name, say logo.png or front.jpeg, the change won’t happen right away unless you force refresh it on browser to clear the cache.
The problem with this one is when you have dynamic updates and your users couldn’t see the change right away b/c of the cache.

The simple fix for this would be appending version at the end of the file name. Like your original html would look like:

img height="200" src="/path/to/image/file.ext" 

Then appending the version at the end

img height="200" src="/path/to/image/file.ext?v=someVersionGoesHere" 

For any backend it would be easy to append the versioning when the image is presented. It could be random number or unix timestamp would work in this case too..

If you are generating the images from javascript, say based on the json response, you can do

var version = new Date()->getTime(); //get the unix timestamp
var path = "/path/to/image/file.ext?v="+version;

$('#image_id').attr('src', path);

Shall do the trick. I used jQuery her but, it is not limited to it..

Select an element with multiple classes jQuery

CSS Classes, as we know are the main drivers in the UI. Since we have only one id per element, our arena or tweak on that area is almost limited.
But classes are possible to be deployed multiple times per element and we can apply independent actions per classes..
Now, when you have two classes assigned and you want to single out that element having two classes in jQuery you would do

$('.class1.class2')

Without any space in between.
Common usage would be with javascript where you would take and put classes based on actions.

Yup!

Mommy look.. Upgrading jQuery breaks live :(

If you have upgraded jQuery to 1.9 then you would have dreaded Uncaught TypeError: undefined is not a function would be barking at you on your javascript console.

The fix
According to the jQuery site, you would need to replace live with on

Say if you have:

$('.selector-class-name').live('click', function(){console.log('
Applications programming is a race between software engineers, who strive to produce idiot-proof programs, and the universe which strives to produce bigger idiots. So far the Universe is winning.
Rick Cook
')});

Then you would have to change this to the new version using on as follows.
*The current on will be passed the event owner as a parameter so, we have to have a way to know the parent of the event owner, in this case the object with class selector-class-name.
If we don’t know the parent we can implement body tag

$('parent-of-object').on('click', '.selector-class-name', function(){
Applications programming is a race between software engineers, who strive to produce idiot-proof programs, and the universe which strives to produce bigger idiots. So far the Universe is winning.
Rick Cook
});

This shall take care of the problem.

jQuery bind/unbind not working on firefox or in some other browsers

So, your jQuery bind is working OK on all browsers and not in firefox?

At least in my case, it worked on chrome and not on FF.

Let me put it using example:

let’s say we want to assign click event to some item with id = ‘bindable’


$('#bindable').bind('click', function(){
      alert ('From the truth and search of truth, I would prefer the later..');
});

this snippet works fine in chrome and others. but in firefox it is NOT.

The culprit is in passing the ‘event’


$('#bindable').bind('click', function(event){//look mom, i pass the event here..
      alert ('From the truth and search of truth, I would prefer the later..');
});

See mode javascript stuffs

Date Picker in jQuery misses next and prev arrow. How to add arrow on jQuery date picker

jQuery date picker missing navigation arrow

Did you add the date picket and it is missing the arrow for next month/year navigation?

I have been there – yea, jQuery missing the arrow for year and month navigation.

If you add the date picker on your project and for some reason you are not seeing the arrow for navigation, do the following:

  1. Go to the site jqueyrUI and download the file.
  2. Then in the css folder you will see the theme
  3. inside the theme, there is an images folder.
  4. Copy the whole folder and put it in you project in the same folder where the jQuery ui css resides and that will take care the problem.

The above is the solution for missing the arrow image in jQuery navigation.

Recommended for You:

You want to learn nodeJs and Angular in minutes? See this step by step guide

Selecting an element with multiple classes? Check this out

Did you upgrade and production is broken? Here is the fix

Dynamically populate select box from JSON in javascript/jQuery

Populating select box with JSON tutorial example

JSON [JavaScriptObjectNotation] has become the defacto standard for web-consumers these days.

I also interact with it in a frequent manner.

The major usage might be when you are interacting with API based websites. Even though there are multiple response types, json is one of the most widely endorsed these days.

Based on the response you can apply it to different parts of the web app.

When would I be using json for select boxes?

Lets say you are calling an API to give you the list of available cars and the API would return the result in json format.

Then you can use that response as a selection in select box or you can also list it as options to be checked in the form of checkboxes and the like.

Node tutorial with http web server

Here is example of using json response used in select box

I will try to give some simple example on using JSON with old school javascript and jquery.
Lets have the following JSON for our example:


var cars=[{"color":"red","made":"toyota","model":"corrola","mileage":"10000"},{"color":"silver","made":"honda","model":"accord","mileage":"160000"},{"color":"white","made":"nissan","model":"maxima","mileage":"12200"}];

Just ordinary simple data to play with.

Using Old School Javascript:

Assuming there is select box with id “dynamic_slct”


var options = '';
slctbox = document.getElementById('dynamic_slct');
for(var i=0 ; i<cars.length ; i++)
{
    var label = cars[i]['made'];
    var model = cars[i]['model']; //or whatever the value you want to show
    var opt = document.createElement('option');
    slctbox.options.add(new Option(label, model));
}

As simple as that, the ‘cars’ should be available on the page being accessible to the javascript that is populating the options. If you are working on PHP, for example, spitting the json_encode(array) would provide what is needed for this

Uisng jQuery


var opt="";
$.each(cars, function(){
   var label = this['made'];
   var model = this['model'];
   opt += ""+model+"";
});
$('#dynamic_slct').html(opt);

find and filter in jQuery when and how to use

Thanks to JQuery, handling javascript has never been easy. Bigger things while working on the client side would be querying the DOM for specific components. Among the tremendously many options, I would discuss the find and filter.
For illustration of the discussion let’s have the following example HTML:

<div class="upper"><p>Upper text goes here</p><div>
<div class="upper"><p>Another <b>Upper text goes</b> here</p><div>
<div class="middle"><p>middle <b>text goes</b> here</p><div>
<div class="lower">lower <b>text goes</b> here<div>
<div class="lower"><p>still another lower <i>text goes</i> here</p><div>

Using Filter

Filter would provide all the given components which are screened by the given condition. the query:
jQuery(‘div’).filter(‘.upper’) would provide two elements of div that have class upper on them. so alert(jQuery(‘div’).filter(‘.upper’).length) would alert two. Changing the class to middle and lower would result one and two respectively.

Using Find

Find, like the filter would provide elements and unlike filter, it would apply filtering on the children of the given component. Here is an example

jQuery('div').find('p').addClass('border-it');

This query would select the ‘p’ tag under every div element and would apply the class ‘border-it’ to the ‘p’ element only. Which means, it would iterate on the given condition on the parent component.

Finding all the bolds and underlining them would be:

jQuery('div').find('p').find('b').css('text-decoration', 'underline');

Also, this can be done ins succinct way as:

jQuery('div p b').css('text-decoration','underline');

How about if we want to select both the parent and the selected child:

In this case the handy method andSelf() would be there. Say if we want to border only the bold text and that of the enclosing div, we would have:

jQuery('div').find('p').find('b').andSelf().css('border', '1px black solid');

jQuery – Simple & Powerful

jQuery seems the new player as far the client side manipulation is the issue. I had always thanked JavaScript for allowing us to do the dirty job on the client side starting from validation to amazing animations and magics – as it was seen on the Google earth, we should due credit.
Then comes Ajax, yup I have loved and played with it and it is so logical. Why do I have to submit the whole page while the intension is to submit only, say, a single value like an email for subscription. Of course it has done even more than that.
And now, jQuery which is a bundle of the two nice tools. JQuery is collection of JavaScript libraries that would make coding easy, fast navigation experience and almost a shortcut to Ajax.
The functions in the jQuery are human friendly and easy to remember.
It is possible to access an element only, or a group of elements or elements under the same class in easier way. Above all uses nicely callback functions – cooool.
All one has to do to start jQuery is to download the library from http://docs.jquery.com/Downloading_jQuery and locate it like any other JavaScript code:
Following this, be ready to plough. The main character in play would be the jquery object itself. Accessing it could be done either by directly calling it or using its alias($) – which is the custom to go. How it does is: first it would select single or group of elements and then apply tasks like editing, hide/show, replacing, assigning new style and many more. Let us use the following simpe XHTML code for illustration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Sample jQuery </title>
<script src="JQuery/jquery-1.3.2.min.js" type="text/javascript" ></script>
<style type="text/css">
.highlight{
background-color: palegreen;
font-family: verdana;
color: black;
font-size: 12px;
width: 300px;
}
.emphasis{
text-weight: bold;
border: solid 1px blue;
width: 300px;
}
</style>

</head>

<body>
<p id="description" class="highlight">This is for the illustration purpose</p>
<p id="attention" class="emphasis">give attention for this</P>
<a href="http://www.devx.com/codemag/Article/40923/0/page/1">More examples</a>
<input type="button" id="toggler" value="toggle" />
</body>
</html>

Basic jQuery statement would have the following format:

<script type="text/javascript">
       $(document).ready( function(){
               logic goes here;
         });
</script>

Here the ‘$’ is an alias for the jQuery object, document is the representation of documents as in DOM. The ready method makes sure if the page is ok to proceed or not.
function() inside the ready() method is the callback function. The beauty begins here, we can define any function of our own as we like.
Lets remove the highlight style from description and assign it emphais
The first part “p#description” would select the paragraph with id description. Had it been “p”, it would select all paragraphs.
In this particular case it is also possible to say (“#description”).
removeClass and addClass are self-explanatory.
The chaining is possible as a dot operated methods because each selection would return an object.
Remember how to toggle in JavaScript? Had to use if .. how about in jQuery.
Lets make a click on the first paragraph to hide and show the second paragraph.

        $("#description").click( function(event){
              $("#attention").toggle();
        });

That is all. A single line would keep our fingers from being tired.

Here, the click method would accept the callback function. This call back function is specific to the call only. Say if I have used (“p”), then when I click on a particular <p>, the click method would be applicable only to the clicked paragraph element.

	$("p#description").click(function(event){
            $(this).hide();$("p#attention").show();
        });
	$("p#attention").click(function(event){
            $(this).hide();$("p#description").show();
        });

The above snippet shows only one paragraph at a time. But it shows them alternatively.

This is just to give a very highlight about jQuery. There are a lot of things especially on the selection area.

The following are are good sources of jQuery tutorial and references
jQuery.com
http://www.devx.com/codemag/Article/40923/0/page/1
http://roshanbh.com.np/2008/03/jquery-benefits-examples-free-ebook.html