Monday, May 06, 2013

HTML Select element manipulation using Javascript - I

SelectBox, the HTML <select> element, is an useful thing which we use on various webpages. Here we would be discussing on the following points with select element.

1. List All options and their values
2. Show selected option's text and value
3. Append new options at the end of the list
4. Add new options at the top of the list
5. Add new options at any position of the list
6. Remove a single options from the list
7. Remove all/multiple options from the list
8. Edit any option at any position within the list
9. Create a copy of the select element and append it to the body.
10. Sorting all options in a Select element

11.  Select/UnSelect all options in a Select element

Here we would be solving each point. Here is the select element :

<select id='selectBox' name='selectBox'>
<option value=''   > Select a Bike Model </option>
<option value='suz'> Suzuki </option>
<option value='duc'> Ducati </option>
<option value='hnd'> Honda </option>
<option value='yam'> Yamaha </option>
<option value='kwk'> Kawasaki </option>
<option value='apr'> Aprilia </option>
</select>



1. List All options and their values :

<script>
// Get the Select element
var p = document.getElementById("selectBox");
var str = "";

// Loop each item
for(i=0; i<p.options.length; i++)
{
  var option = p.options[i].textContent ? p.options[i].textContent : p.options[i].innerText;
  str +=  p.options[i].value + " : " + option + "\n";
}

alert( str );
</script>


The output would be :

 : Select a Bike Model
suz : Suzuki
duc : Ducati
hnd : Honda
yam : Yamaha
kwk : Kawasaki
apr : Aprilia

The first does not have a value specified, hence it is showing nothing in the first row of output. To get the option text, we use textContent for non-IE browser and innerText for IE. Option index starts from 0.

2. Show selected option's text and value

First, we create a function which takes option number as its argument and shows that option on screen. Option list is an array of all the texts starting with index zero.

<script>
var option = getOption ( 2 );

function getOption( option_no )
{
    // Get the Select element
    var p = document.getElementById("selectBox");

    // Declare empty object
    var str = new Object;

    // Try to get that option
    if( p.options[ option_no ] == undefined )
    {
       /// That index is invalid
       /// Hence Empty Object would be returned
    }
    else
    {
      /// Valid Index has been used
      str.option = p.options[option_no].textContent ? p.options[option_no].textContent : p.options[option_no].innerText ;
      str.value  = p.options[option_no].value;

    }

    return str;
}
</script>


The code above is quite self-explanatory. We have also checked whether the passed index is invalid or not. For example, if we call :

var option = getOption( 32 );  /// Out of bound Index

an empty object would be returned to "option" variable. The expression :

p.options[ option_no ] == undefined

checks whether that indexed location exists or not within the options array.


When any option is selected, the 'selectedIndex' property of the select element automatically holds the index number of that item. Hence to get the value and text of the selected item, we need to write the following statements ...

var s = p.options.selectedIndex;
var opt2 = get_option( s );
alert(opt2);

We are simply passing the index of selected option item to the get_option function and the return string ( consisting option text and value ) is collected in variable opt2.

3. Append new options at the end of the list

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Create a Dynamic Option called Hyosung
var o = new Option("Hyosung", "hyo");

// Append the new option to the select element
p.appendChild( o );
</script>


We are just creating new option object with the keyword 'new', and the "Option" constructor call takes 2 arguments - Option Text and Option Value. Then we are appending the new option object to SelectBox element. This new option is automatically appended at the end of the list.

The above code may not work in old versions of IE (in IE9 it is okay). In that case we can write the below code which would run in all browsers without any problem.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Create a Dynamic Option called Hyosung
p.options[ p.options.length ] = new Option("Hyosung", "hyo");
</script>

Another function add() would add new options to the list at the last position.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// use add() method
p.options.add( new Option('Hyosung', 'hyo') );
<script>


Or we can add new options the following way ... this would run on all browsers including IE 7 and 8.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Create new Option element
var opt = document.createElement("option");

// Set properties
opt.text = "Hero";
opt.value = "hro";

// Use add() method to add new options
p.options.add( opt );
</script>



4. Add a new options at the top of the list

We can do it in 2 ways, 1 is long and second is very short. Both the methods are discussed below.

1. In this method, we are going to follow these steps..
   a. Copy all the options of the selectbox to an array
   b. Create a new option object
   c. Insert the new option at the beginning of the array
   d. Remove all options from the selectbox
   e. Insert all options from the array to selectbox element using appendChild() method

Check the code below.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Copy all the options to an array
var str = [];
var i;

// We are ignoring the "Select a Bike Model" option at index 0
for( i=1; i<p.options.length; i++)
{
  str[i] = p.options[i];
}

// Create a Dynamic Option called Hero
var o = new Option("Hero");

// Add value to it
o.setAttribute("value", "hro");

// Insert the new option at the beginning of array
str[0] = o;

// Remove all options from the selectbox
p.options.length = 1;  // "Select a Bike Model" option remain untouched

// Insert all options fom array to Select Box
for( i=0; i<str.length; i++)
{
  p.appendChild( str[i] );
}

</script>


2. This was a long road to achieve what we wanted. Now is the tun for the short-cut route. Check the second method ..
   a. Create a new option object
   b. Find a position where we would be inserting the new option
   c. Insert the new option into the selectbox using insertBefore() method. insertBefore() takes 2 parameters, new node and reference node and as a result, the new node is inserted before the reference node. If reference node is null, the the new node is inserted at the end of the list of options.

Check out the javascipt implementation below.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Create a Dynamic Option called Hero
var o = new Option("Hero");

// Add value to it
o.setAttribute("value", "hro");

// Get the first option, zeroth option is "Select a Bike Model"
var n = p.options[1];

// Insert the new option directly
p.insertBefore( o, n);
</script>


The above methods would not give proper results in older versions of IE. On IE9, they would work perfectly. We can have the following code for getting the proper results in IE7/IE8.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Copy all the options to an array
var str = [];
var i;

// We are ignoring the "Select a Bike Model" option at index 0
for( i=1; i<p.options.length; i++)
{
  str[i] = p.options[i];
}

// Create new Option
str[0] = new Option("Hyosung",'hyo');

// Increase the Option List Count
// Create a placeholder in the select element

p.options.length ++;

// Now copy all option nodes from array to Select element
for( i=1; i<p.options.length; i++)
{
  p.options[i] = str[i-1];
}
</script>


The above code ran well in IE7/IE8. It is quite self-explanatory. We area creating an array and pushing all the options to that array. After that, we create a new Option object and push it to the array. Then we create a new placeholder in the option list of the select element to fit in the new option. Finally we copy all the items of array to the select element's options list. We can use the same method to insert any new Option in the middle position of an option list. Insertion in the middle of such option list is discussed in point 5 below.

Notes :
We can use innerHTML property of select element to insert new options but this would remove all old options.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Overwite everything inside
p.innerHTML = "<option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option>";
</script>


The above code would insert 3 new options into the select element and erase all old options. However this does not work in IE older versions. The innetHTML method really comes handy when we fetch dynamic options from an ajax call. After we receive the bunch of options as ajax response, we can simple assign it to the innerHTML property of a select element. This is shown below..

<script>
document.getElementById('selectBox').innerHTML = ajaxResponseText;
</script>


5. Add new options at any position of the list

Using insertBefore() method we can insert a new option at any position into a select element. If the second parameter to insertBefore() is null, then the new option is added at the end of the list of options. Check out the code below.

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Create a Dynamic Option called Hero
var o = new Option("Hero");

// Add value to it
o.setAttribute("value", "hro");

// Insert "Hero" before "Kawasaki"
// Locate the "Kawasaki" node first

var refer_node = p.options.item(5);

// Now Insert "Hero"
p.insertBefore( o, refer_node );

// Now insert it before "Aprilia"
refer_node = p.options.item( 2 );
p.insertBefore( o, refer_node );

// See THAT the new node o has been moved
// From its previous place (place before Kawasaki)
// to new place (place before Aprilia)


// Remove all Old options
p.options.length = 0;

// Inserts at the end
p.insertBefore(o, null);

/// Multiple Inserts with same node is not possible.
/// A node already inserted, cant be inserted again

p.insertBefore(o, null); // Ineffective
p.insertBefore(o, null); // Ineffective

/// Use cloneNode() to clone a node and insert
var o2 = o.cloneNode();
p.insertBefore(o2, null); // Works
</script>


The above code works in IE9 and other browsers like Firefox and chrome. For IE7/IE8, we can use the method discussed in point 4 above.

Notes ::
1. To Update any old option with new one, we can write the following code :

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// OverWrite the old Option with new item
p.options[3] = new Option('Option Text', 'Option Value');
</script>


2. To Insert empty elements to the option list, write following code

<script>
// Get the Select element
var p = document.getElementById("selectBox");

// Insert empty elements at the end
p.options.length = 100;
</script>


The above code increases the option array length to 100 which means if it already has 7 elements in it, 93 more empty options are added to it.

3. We can populate a select element taking values from an javascript object as shown in below example.. This runs on all browsers.

<script>
// Define Object
var obj = { duc:'Ducati', suz:'Suzuki', apr:'Aprilia' };

// Get the Select element
var p = document.getElementById("selectBox");

// Iterate Object properties
for(var i in obj)
{
    // Create new Option element
    var opt = document.createElement("option");

    // Set properties
    opt.text  = obj[i];
    opt.value = i;

    // Add it to Options array
    p.options.add( opt );
}
</script>


Check the next part here.

No comments: