Tuesday 6 November 2012

"Use same function by using element ID":Pass id as an argument to use function for different events on different elements


 we can also use a common function that binds to different event associated with different elements and we only pass id and access the function by identifying id in function argument like this


function ValidateForAllValue(id )
{
  var str=""
  $("select#"+id+" option:selected").each(function ( )
  {
    if($(this).val() =="Defined" )
    {
 
     str=str+$(this).val();


    }

    if(str=="Defined" && $(this).val() != "Defined")
    {
 
     alert("Invalid selection: option 'All' can not be selected with any other option");
 
 
        $(".AllClass").val([])
 
      return false;
    }
    if ($(this).val() == "None")
    {
      $(".AllClass").val([]);
 
      alert("Select some valid option");
 
    }
  });
};


Here this function displays alert for the element if  user select "All" along with other option.Therefore we can call this function for any select list by passing on onclick attribute like this:

<select onclick="ValidateForAllValue(this.id)">



$(this) always works on iteration

You cannot access  an element with $(this)  at event binding like this:

<select onclick="fun()">
....


fun()
{
 $(this).each(function ( )
{

.....

........

Reason : It works in iteration to refer to the element
                    $("select#"+id+" option:selected").each(function ( )
                   {
                          if($(this).val() =="Defined" )
                           {
   
                                    str=str+$(this).val();

                                   .............................

or you can also use that element at finction calling like this.....

<select id="xyz" onclick="fun(this.id)">