Tutorial: jQuery Select Box Manipulation Without Plugin

In jQuery, working with select box required some additional knowledge and interaction with jQuery. You may have some problem manipulating select box during your web development on jQuery. In this article we will discuss how you can solve this without any additional plugin to kill efficiency.

Create Selext Box In jQuery

Create a select box is very simple and straight forward. Just write a string with the normal select tag and a select box is created in jQuery

jQuery('#some_element').append('<select></select>');

I bet everyone would have tried this and it work. However, manipulating might be a more challenging task.

Add Option In Select Box With jQuery

One easy way is to create a string with the whole element and create it straight away

//obj is the list of option values
function(obj)
{
	var create = '<select id="test">';
	for(var i = 0; i < obj.length;i++)
	{
		create += '<option value="'+obj[i]+'">'+obj[i]+'</option>';
	}
	create += '</select>';
	jQuery('#some_element').append(create);
}

Another way to create a list of elements is to create its option and append it in using pure jQuery.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	jQuery.each(obj, function(val, text) {
		jQuery('#'+id).append(
		jQuery('<option></option').val(val).html(text)
	);})
}

You may not be familiar what i wrote above. Hence, a more javascript approach is shown below.

function(id, obj)
{
	jQuery('#some_element').append('<select id="'+id+'"></select>');
	for(var i = 0; i < obj.length;i++)
	{
		jQuery('#'+id).append('<option value="'+obj[i]+'">'+obj[i]+'</option')
	}
}

Get Select Box Value/Text In jQuery

Sometimes we want to know what is the value of the selected option. This is how we do it. Please bear in mind that there shouldn't be any spaces between the : and selected.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').val();

On the other hand, we can get the text of the option by doing this.

//#selectbox is the id of the select box
jQuery('#selectbox option:selected').text();

What if you know the value of the options you want to get instead of the one selected?

//#selectbox is the id of the select box
$("#selectList option[value='thisistheone']").text();

How about the first element on the select box?

//#selectbox is the id of the select box
$("#selectList option:first").text()

How about the n element on the select box?

//#selectbox is the id of the select box
$("#selectList option:eq(3)").text()

How about getting all elements but the first and last one in a select box?

//#selectbox is the id of the select box
$("#selectList option:not(option:first, option:last)").each(function(){
$(this).text();
});

Get Multiple Selected Value/Text In jQuery Select Box

Now we want to try to retrieve multiple selected values, we can do it easily with the following code.

	jQuery('#some_element:selected').each(function(){
		alert(jQuery(this).text());
		alert(jQuery(this).val());
	});

How about storing these values?

	var current = [];
	jQuery('#some_element:selected').each(function(index, selectedObj){
		current[index] = $(selectedObj).text();
	});

This way we eliminate the additional index needed to follow through the loop! How about shorten the cold a bit?

var foo = jQuery('#multiple :selected').map(function(){return jQuery(this).val();}).get();

This way we eliminate the need to create an array.

Remove Element In Select Box With jQuery

So we can get and add element into the select box. How about remove them? Basically, you will need to use one of the get element method describe above before applying the remove instruction.

jQuery('#selectbox: selected').remove();

Here we will remove all elements except the first and last one.

//#selectbox is the id of the select box
$("#selectbox option:not(option:first, option:last)").remove();

Select an option in the select box with jQuery

If you want to select an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', 'selected');

all option will be selected in this case.

UnSelect an option in the select box with jQuery

If you want to unselect an option in the select box, you can do this.

jQuery('#selectbox option[value="something"]').attr('selected', false);

all option will be unselected n this case.

OnChange find selected option from the select box

onchange find select box selected item.

$('#selectbox').change(function(){
	var val = $(this).find('option:selected').text();
	alert('i selected: ' + val);
});

onchange find select box selected items.

$('#selectbox').change(function(){
	$(this).find('option:selected').each(function () {
		alert('i selected: ' + $(this).text());
	}
});

Summary

There are definitely other tricks to manipulate select box. The above are just some of it.

The Secret Arguments Array in JavaScript

Well, this is not really a secret to be exact. Many experience programmers who have worked with JavaScript for many years will surely come across arguments array. Some book may even forgotten the existence of arguments array since it is not widely used. Hence, i believe majority of JavaScript programmers do not actually know the existence of such array in JavaScript. So allow me to explain what is arguments array.

Arguments Array

An arguments array is a predefined array used within a function in JavaScript. Whether you used it or not it will still exist within that function. The main advantage of using arguments array is the unlimited number of argument or parameter you can pass into a function. Let's consider the following example,

function example()
{
	var sum = 0;
	for(i = 0; i < arguments.length;i++)
	{
		sum += arguments[i];
	}
	alert(sum); //45
}
example(1,2,3,4,5,6,7,8,9,0);

i find that the above example will simply get the idea through how arguments array worked. It is an array so whatever we passed in via arguments will be placed into an arguments array within the function. Then, we simple just used it. The above example is an simple addition function. You can see another example at override ‘this’ object in JavaScript

Detect Arguments

What if we want to use the arguments array in certain circumstances but not all the times? Preload with jQuery shows one particular function that uses an array or parameter depend on how users want to use that function (now, you might have guess how a library such as jQuery allows multiple different parameter for a single function). In order to do that, we have to detect what arguments or values been passed on to the function.

In JavaScript, we can detect a particular value by using comparison operators (===, ==, !=, etc.) but there are also other techniques to detect these arguments. We can use in operator which detect whether a given value is in the arguments array (in operator is not widely supported. Thus, you don't see many using it). There are also typeOf operator which determine what is the type of the value (string, object, int, etc.)which you can see from Preload with jQuery article. Lastly, there is Autocasting operator which evaluate whether a variable has a value (NaN, 0, false, undefined, null, or an empty string are considered as no value). Let's look at each new detection method example that i mention here.

//Detect whether there is a "hello" member in the arguments array: 
var parameter = 'hello' in arguments? arguments : "";

//Detect whether arguments contains at least one argument
var parameter = typeof arguments[0] != 'undefined'? arguments : "";

//Detect whether the user passed an object(can be array) or a list of arguments
var parameter = (typeof arguments[0] == 'object')? arguments[0] : arguments;

//Detect whether there is an arguments passed into the function and assign the number of arguments into the variable
var parameter = arguments.length || "";

Summary

Using Argument Array is great as we are not restricted by the number of parameter on a given function. However, many online tutorial on basic JavaScript no longer practice this since it is said that this has been depreciated with new browsers emerged but its still usable in JavaScript up till today (who said its depreciated!).

Tutorial: How to override ‘this’ object in JavaScript

Have you ever experience a time when the calling object 'this' needed to be override and somehow you just couldn't do that? You tried left hand assignment but it just won't work? wondering how can 'this' object be overridden in JavaScript but can't find the correct answer on Google? This article will explain how this can be done.

Left hand assignment

Ever tried left hand assignment to override 'this' object?

var obj = document.getElementById("button");
this = obj

It will fail and gives you 'invalid assignment left-hand side'.

Using Call() to override 'this' object

There is a function in JavaScript, Call() which can help you override 'this' object or specify the 'this' object. Let's consider the following example,

function example(a,b)
{
	this.value == 'button'?alert(a):alert(b);
}
var textobj = document.getElementById('input_relink');
example.call(textobj, 'It is a button!', 'It is not a button');

We look at a text box and check whether the user key in 'button'. But we uses 'this' object to verify the input text in the function example which takes in two parameter as shown above. The Call() method is used whenever you wish to override 'this' object which is placed at the first parameter and the rest of the parameter will be exactly the same as the method parameter. Hence, we used the function in this way for the above example because it has two parameter.

//override 'this' with object 'textobj'
example.call(textobj, 'It is a button!', 'It is not a button');

If we have another function which takes in 3 parameter, we will do this.

function example(a,b, c)
{
	this.value == 'button'?alert(a):alert(b);
	alert(c);
}
var textobj = document.getElementById('input_relink');
example.call(textobj, 'It is a button!', 'It is not a button', 'Completed');

You can also used it without parameter like the one illustrated below,

var o = { x: 15 };
function f()
{
    alert(this.x);
}
f.call(o);

Using Call() method restrict your variable given on the method. On the other hand, we can use another method Apply() which override the 'this' object giving the second parameter as an array.

Using Apply() method to override 'this' object

The difference between call and apply method is the parameter needed to use them. For Call() method it depends on the parameter of the function as shown above. But for Apply() method it can have more than the amount of parameter in the function (since it takes in an array). Similarly, the first parameter of both methods are used to override 'this' object. Let's consider the following example,

var o = { x: 8 };
function example()
{          
    // arguments[0] == object 
	var sum = 0;
    for(var i = 1; i < arguments.length; i++)
    {
       sum+=arguments[i]
    }
	alert(sum+ this.x);
}
example.apply(o, 1, 2, 3, 4)

I am using the depreciated argument array to look through the argument being passed into the function, sum them up, alert to the user. Similarly, i can do this using an array.

var o = { x: 8 };
function example(a, b, c)
{          
	alert(this.x+a+b+c);
}
example.apply(o, [1,2,3])

Pretty simple isn't it?

Tutorial: How to add preloader with loading image in a gallery using jQuery

In my previous article on understanding preloading for components, we talk about a lot about preloading. If you are seeking for other methods you may want to visit that article. In this article, i will demonstrate how to perform a preload with those loading in progress image in a gallery using jQuery.

Requirement

The gallery used will be the one at How to create your own continuously slide effect plugin with jQuery. But if you have your own gallery, this can safely be skipped.

Concept

The concept of preloading images with a loading image is pretty easy. The important thing we need to know is onload and onerror functionality in JavaScript. onload is here to tell us whether the picture is ready and onerror is here to tell us whether the picture cannot be loaded due to various reason. With some additional checking and animation to make it look nice.

The Code

HTML

I have added one additional div block, 'loading' into the gallery and added the image link in the picture instead of image tag.

<div id="frame">
	<div id="container">
		<div class="box" id="box1">images/1.jpg</div>
		<div class="box" id="box2">images/2.jpg</div>
		<div class="box" id="box3">images/3.jpg</div>
		<div class="box" id="box4">images/4.jpg</div>
		<div class="box" id="box5">images/5.jpg</div>
		<div class="box" id="box6">images/whatever/6.jpg</div>
	</div>
<div id="prev"></div>
<div id="next"></div>
<div id="loading"></div>
</div>

The sole purpose of doing this is to load the page faster and enable any window.onload function. This way, user will not have to wait a few second for the overall page to load. Take note that i purposely write a wrong URL for box id 'box6' so that it won't load.

CSS

Since i have added a new div block, i will have to declare its CSS rule.

#loading
{
	display: none;
	position: absolute;
	height: 234px;
	width: 234px;
	margin-top: -117px;
	margin-left: -117px;
	left: 50%;
	top: 50%;
	background: transparent url('../images/loading.gif') no-repeat 100% 100%;
}

Basically i have align the loading image at the center of the gallery and hide it for the time being.

jQuery

I i have just added the following one line after the animation has completed,

			$("div#container").animate({marginLeft: i*op.containerW+"px"},op.duration, function(){
			var imgObj = getImg(pathObj[0-i]);
			});

once the animation is over, we can start preload the images out to show our users. And the two resuable and cross browser methods i have made for myself in case of future gallery are getImg() and loadImg(). Let's first talk about getImg.

	function getImg(obj)
	{
		url = $(obj).css({"display":"block", "visibility":"visible"}).html();			//get the image url from the div block
		loaded = false;										//check whether image has been loaded
		if(url.search(/<.*/) != -1)							//search for opening tag, doing /'<img.*/>'/ doesn't work in IE7 and Opera somehow.
		{
			loaded=true;									//found opening tag, assume its loaded
			tmp = $(obj).children();						//get the img tag obj
			url = $(tmp[0]).attr("src");						//retrieve the url
			if(tmp[1] != undefined)							//check whether there is a second block in the children of the div block (this is added in loadImg when it fail)
				loaded = false;								//there is an error message, we try to load again
		}
		if(!loaded)
			loadImg(url,obj, "#loading", "there seems to be an issue, try again later");
	}

In getImg, it takes in one parameter, obj which is the current div block we are looking at. Basically, what the above method do is to retrieve the image link provided in the div block, check whether this block image has been loaded and determine whether it needs to be loaded. This method also provides a second chance for user to reload the image again which depend on loadImg(). Comment are written in the code.

loadImg is the preloading that takes place,

	function loadImg(url, obj, loading, msg)
	{
		$(loading).css({"display":"block"}).animate({opacity:1},1000);					//display the loading in progress image
		$(obj).html("<img src='"+url+"' width='500px' height='350px'/>").css({opacity: 0});	//throw in the image into the div block
		var tmp = $(obj).children();													//gets the image obj we just thrown in
			tmp[0].onload = function(){													//when the image has complete loaded
				$(obj).animate({opacity:1},1000);										//display the image
				$(loading).animate({opacity:0},1000).css({"display":"none"});				//hide the loading in progress image
			}
			tmp[0].onerror = function(){												//when the image fail to load for various reason
				$(this).css({"display":"none"});											//we hide the image that fail
				$(obj).html($(obj).html()+"<div>"+msg+"</div>").animate({opacity:1},1000);//provides a message to the user instead
				$(loading).animate({opacity:0},1000).css({"display":"none"});				//hide the loading in progress image
			}
	}

This method takes in four parameter which can join together with the first method and become one but i prefer them to be seperated. What it does are commented above and the parameter are listed below,

  • url: the image url. eg, 'http://hungred.com/hello.jpg' or images/hello.jpg
  • obj: the current div block with the image url on it.
  • loading: the loading in progress image block id. eg, '#loading'
  • msg: the image or message when the url image fail to load. eg, 'fail to load image, try again later'

As we can see the first image doesn't load yet as getImg() only gets fire up whenever the user clicked the next or previous button. What we do is to provide the first element div block to getImg() as shown below,

getImg(pathObj[0]);

where pathObj is the list of div blocks with the class 'box' as shown on the HTML section.

Additional preloading

if you want to preload further, you can try to add the code mention in preload all images in jQueryafter document.ready() to preload in advance all images and stored it to their cache. In this way, user might not even need to wait a millisecond for an image to load up.

The Demo

The demo and files are provided below,

Conclusion

Well, the purpose of this article is to share with you how i make a preloader in a gallery with jQuery and also provide my code snippet for you to integret this small method into your gallery to make your page with gallery more responsive.

Preload with jQuery

Recently i wrote an article on understanding preloading and right after completed writing that article, I'm on my journey to create a jQuery gallery for a project. At that time, i found an interested method written by Matt on preload with jQuery. And i think this should be adopt by many programmers out there. But basically, he creates a preload function for jQuery as shown below

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

So, once your jQuery is ready, we will fire up preload function as shown below,

$.preloadImages("image1.gif", "/path/to/image2.png","some/image3.jpg");

Pretty neat right? But for me to add these path one by one into the preload function is not my kind of meat. So i will prefer the following code which also takes in array into consideration

jQuery.preloadImages = function() {
var a = (typeof arguments[0] == 'object')? arguments[0] : arguments;
for(var i = a.length -1; i > 0; i--) 
{
	jQuery("<img>").attr("src", a[i]);
}

And i will use it like this,

var images = [];
$('.box').each(function(){
	images.push($(this).html());
});
$.preloadImages(images);

basically it retrieves all the images with class .box and placed into an array to be preloaded. Why do i want it to take in an array instead? Because i don't use image tag such as

<img src="image1.gif"/>
<img src="image2.png"/>
<img src="image3.png"/>

instead i usually gallery it like this,

<div>image1.gif</div>
<div>image2.png</div>
<div>image3.png</div>

The reason is it loads up faster. And all bandwidth will be dedicated to load up the page instead of distributing some to the images that might not be showing out yet. There are also many advantages and disadvantages of doing this but let's keep it this way. Furthermore, the images are usually populated by server which resist in HTML. It is always good to have alternative!