Tuesday, May 14, 2013

HTML Select element manipulation using jQuery - II

We have already discussed a few points on Select element manipulation with jQuery in my previous article, here we would be discussing few more points.

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

<select id='selectBox1' name='select' size='10' multiple='multiple'>
 <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>


6. Remove a single option from the list

If we want to remove the " Aprilia " from the list, we can take following steps...

i. Iterate through the loop options
ii. If option's text matches with text, then we remove it.

Check the jquery implementation..

<script>
// Use each() function
j("$selectBox1 option").each(

// Callback function for each()
function()
{
 
  /// Option Text is being matched here
  if( j(this).text() == " Aprilia " )
   {
      // Remove the Option
      j( this ).remove();

      // Break;  -- WE can't write a BREAK here
      // Hence each() function will iterate till
      // the last option in th list even if
      // an option is found and deleted.
   }

} // CallBack ends

); // each() ends
</script>


However, we can use a different selector to select an option directly and remove it.

<script>
// Remove the second child from the top
j("#selectBox1 option:nth-child(2)").remove();

// Get total count of all the options
alert ( j("#selectBox1 option").length );
</script>


As discussed earlier, children indexes start from 1 for nth-child selector.

Suppose, we need to delete option " Suzuki " immediately before the last option " Yamaha ". We can use another approach other than the option text matching method discussed above. Check the code below.

<script>
// Get total count
var l = j("#selectBox1 option").length;

// We need to remove the item immediately before index l
l = l-1;

// Build the selector
var str = "#selectBox1 option:nth-child(" + l + ")" ;

// Now remove the item
j(str).remove();

</script>


For a long list with 20000/30000 options, we can surely use the above method.

Here is another approach which is much easier in case we want to delete items/options closer to last item or first item.

<script>
// Get the previous item to the last item
j("#selectBox1 option:last").prev().remove();

// Or we can refer to as many previous items as we wish
j("#selectBox1 option:last").prev().prev().prev().prev().remove();
</script>


7. Remove all/multiple options from the list
To remove all options from a listbox, we can write the following statement...

<script>
// Remove all options at one go
j("#selectBox1 option").empty();
</script>


But the above statement clears all the option texts, the option elements still exist with their respective values. This happens because we have used a wrong selector. "#selectBox1 option" means we referring to all options under "#selectBox1" select element and clearing each of them. And as a result, all option elements are cleared off their texts. The right syntax would be :

<script>
// Remove all options at one go
j("#selectBox1").empty();
</script>


To remove all selected options from a list box, we need to write the following jQuery...

<script>
// Remove all Selected options at one go
j("#selectBox1 option:selected").remove();
</script>


The selector "option:selected" refers to all options in the list which are selected. Another longer approach..

<script>
j("#selectBox1 option:selected").each( function(){ j(this).remove();} );
</script>


Here, we are iterating each selected item with each function... and then delete item.

See, how easier it is to do with jQuery. It would have been much difficult to achieve the same thing as discussed in article HTML Select element manipulation using Javascript - II.

8. Edit any option at any position within the list

Suppose, we want to edit the first option " Aprilia " and change it to "BMW", we can use the jQuery text() and val() functions for achieving this.

<script>
j("#selectBox1 option:first").text(" BMW ").val("bmw");
</script>

The selector "option:first" refes to the first item in the list, the text() function changes its content text while the val() function changes its value. More complex statment can be built like ..

<script>


// refer to 3rd option, then 2 prev() call would
// get us to the fist option itself.
j("#selectBox1 option:nth-child(3)").prev().prev().text(" BMW ").val("bmw");
 

</script>

9. Create a copy of the select element and append it to the body

With jQuery, solving complex tasks like this becomes very easier. Check the following code...

<script>
// Create a clone of existing select element
var p = j("#selectBox1").clone();

// Now append it to document body
// document.body is Native JS
j( p ).appendTo( document.body );

// Now try to append again
// j(document.body) is jQuery
// But this does not seem to work
// Same node can not be inserted again
j( p ).appendTo( j(document.body) );

// Workaround ?? Try this ...
j( j(p).clone() ).appendTo( j(document.body) ); // It works

</script>


An node/element, after its creation, can be inserted to the HTML DOM only once. Further insertion statements does not successfully insert new node.

The above code, clones a select element and inserts into HTML DOM but it creates multiple select element with same ID. Hence we must change newly created element's ID to something else as shown in the example below.

<script>
// Create a clone of existing select element
var p = j("#selectBox1").clone();

// Now set its ID property
j( p ).attr('id','selectBox2');

// Append to an existing form with ID 'frm'
j( p ).appendTo( j( "#frm" ) );

// Create another ANother
j( j(p).clone().attr("id","selectBox4") ).appendTo( j("#frm") );
</script>


Notice, we are adding the "id" attribute to a cloned node and then appending it to an existing form on the document body.

10. Sorting all options in a Select element

We had to do huge stuffs while achieving this with Javascript. With jQuery, we have to follow similar steps but we would write lesser statements. Check out the code below..

<script>
// Create an array of all option nodes
var p = j("#selectBox1 option");

// Sort the array of nodes according to
// their TEXT content
p.sort(function(a,b) {
    if (a.text > b.text) return 1;
    else if (a.text < b.text) return -1;
    else return 0
})

// Now clear the Select element
j("#selectBox1").empty();

// Re-build all options into the Select element
j("#selectBox1").append( p );

</script>


Check the previous part Here.

For having filtering options on a select element, visit this. It has some really great example of a jQuery filtering plugin usage.


11. Selecting/Unselecting all options in a Select element

This is achievable when it is a Multi-select Selectbox element. To do this, we need to assign selected='selected' to each option within the select element. Check the code below.

// Select All Options
jQuery("#selectBox1 option").each(
   function()
   {
     // Add Attribute
     jQuery(this).attr('selected','selected');
   });

// Un-Select All Options
jQuery("#selectBox1 option").each(
   function()
   {
     // Add Attribute
     jQuery(this).removeAttr('selected');
   });

No comments: