Monday, May 13, 2013

HTML Select element manipulation using jQuery - I

We have already discussed select element manipulation with javascript, here we would be solving similar problems using very popular Javascript Framework called jQuery. Using jQuery minimizes the cross-browser conflicts, saves lot of time as we don't have to write long native Javascript statements. jQuery statements are a bit complex, but very compact which means a few lines of jQuery may take the workload of hundred lines of Javascript.

Check the HTML below, it contains the select element which we would be working upon.

<select id='selectBox1' name='select'>
 <option value='apr'> Aprilia </option>
 <option value='duc'> Ducati </option>
 <option value='hro'> Hero </option>
 <option value='hnd'> Honda </option>
 <option value='hyo'> Hyosung </option>
 <option value='kwk'> Kawasaki </option>
 <option value='suz'> Suzuki </option>   
 <option value='yam'> Yamaha </option>
</select>


1. List All options and their values

<!-- LOAD JQUERY LIBRARY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type='text/javascript'>
var j = jQuery.noConflict(); // Avoid Collisions among Libraries

// Define a string
var str="";

// Iterate and Fetch each options and their values
j("#selectBox1 option").each(function(){

  str += j(this).val() + ":" + j(this).text() + "\n";

});

// ALERT
alert(str);
</script>


The code above is much easier to remember and write. j("#selectBox1 option") means we are referring to all option elements contained by the element with ID 'selectBox1'. To access each of the options, we use jQuery each() function which takes a callback function means when jQuery access a single option element it would execute the callback function's contents. val() function returns the option value and text() function returns option text.

To access a paticular option whose value (say, 'suz') is known to us, we can use the following jQuery ...

alert( j("#selectBox1 option[value='suz']").text(); ); 

// Would return " Suzuki "

The equivalent Javascript would be ::

alert( document
.querySelectorAll("#selectBox1 option[value='suz']") .item(0).innerText ) ;

The above statement uses "innerText" would run perfectly on IE8 onwards. To get it run on other browsers, 'innerHTML' or 'textContent' can be used. Because of such browser compatibility issues, developers prefer jQuery to native Javascript.

2. Show selected option's text and value

It is just a one line code..

<script>
alert( j("#selectBox1 option:selected").val() + ":" + j("#selectBox1 option:selected").text() );
</script>

If the select element was a listbox with multiple option selection capability, the we need to give little more effort to get all the selected item's text and value. Check the example below ..

<select id='selectBox1' name='select' multiple='multiple' size='10'>
 <option value='apr'> Aprilia </option>
 <option value='duc'> Ducati </option>
 <option value='hro' selected='selected'> Hero </option>
 <option value='hnd'> Honda </option>
 <option value='hyo'> Hyosung </option>
 <option value='kwk' selected='selected'> Kawasaki </option>
 <option value='suz' selected='selected'> Suzuki </option>   
 <option value='yam'> Yamaha </option>
</select>


Check that " Hero ", " Kawasaki " and " Suzuki " options are selected. Now the jQuery would be like this ::

<script>
// Define a string
var str="";

// Iterate and Fetch each of selected options & their values
j("#selectBox1 option:selected").each(function(){

  str += j(this).val() + ":" + j(this).text() + "\n";

});
// ALERT
alert(str);
</script>


The above code alerts the message as per our expectation... all selected option text and their values are shown.

3. Append new options at the end of the list

A single jQuery statement is sufficient to do this. Check this out..

<script>

j("<option value='bmw'> BMW </option>").appendTo("#selectBox1");

</script>


A new HTML is being referred to when we say j("<option value='bmw'>BMW</option>") which is then appended to the element with ID "selectBox1" using the appendTo() function. We can write the same thing using "append()" function as shown below ..

<script>

j("#selectBox1").append("<option value='bmw'> BMW </option>");

</script>


If the select element does not have any options in the beginning, we can create new options using the above methods. Needless to say that this would work on all browsers including IE7 and IE8.

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

Similarly We can use the "prepend()" and "prependTo()" functions to insert new options at the beginning of the option list.

<script>

// USE prepend() function
j("#selectBox1").prepend("<option value='bmw'> BMW </option>"); 

// USE prependTo() function
j("<option value='bmw'> BMW </option>").prependTo("#selectBox1");

</script>


5. Add new options at any position of the list

Suppose, in a case where we need to insert a new option "BMW" after first option "Aprilia", we can write the following code...

<script>
// Get the option containing "Aprilia"
var t = j("#selectBox1").find("option:contains('Aprilia')");

// Now insert new option after it
j(t).after("<option val='bmw'> BMW </option>");

// Insert the option before it
j(t).before("<option val='bmw'> BMW </option>");
</script>


The node t should be converted to jQuery node by wrapping a j() around it.

Options can be accessed through its index also as we did with Javascript in the other article. It is shown below..

<script>
// This would return Aprilia option's text ( First Child )
var opt = j("#selectBox1 option:nth-child(1)").text(); 
</script>


We use nth-child selector and children indexes start with 1 instead of 0. The first and last child can be accessed using ":first" and ":last" selectors respectively.

<script>
// This would return first option "Aprilia"
var optf = j("#selectBox1 option:first"); 

// This would return last option "Yamaha"
var optl = j("#selectBox1 option:last");  

// Insert a new Node before the first option "Aprilia"
j( optf ). before ("<option value='peu'>Peugeot</option>");

// Insert a new Node after the last option "Yamaha"
j( optl ). after ("<option value='lml'>LML</option>");

// Insert a new node before 2 nodes to last option "Yamaha"
j( optl ). prev() . prev() . before ("<option value='nrt'>Norton</option>");

// Insert a new node 2 nodes down to first option "Aprilia"
j( optf ). next() . next() . before ("<option value='mtt'>MTT</option>");

</script>


All the above codes should run on all browsers. Check the part II of this article here. Check  Implementation in native Javascript of above problems here.

No comments: