Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First option automatically selected when select box with JQuery Multiselect UI by Eric Hynds is updated dynamically

Im using the JQuery UI multiselect plugin by http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/ to dynamically append elements to a select box

//Make filter cars multiselect
$("#cars_filter").multiselect({noneSelectedText:'Select cars'});

function populateCarfilter(){
    var opts="<option value=''>Select cars</option>";
    $.each(markers, function(idx, mar){
      if(mar.getVisible() && mar.get("car"))
     opts+="<option value='" + mar.get("id") + "'>" + mar.get("driver") + " - " + mar.get("car") + "</option>";
    });

    if($("#cars_filter").html()!=opts){
      var id = $("#cars_filter").val()
      $("#cars_filter").html(opts);
      $("#cars_filter").val(id);
      $("#cars_filter").multiselect('refresh');
    }    
}

populateCarfilter(); //This gets called every 2 secs automatically by SSE (server sent events)

Now, im facing a strange problem. The first option in the select box gets selected automatically everytime the select box is updated. Any way to fix this problem ?

Thank You

like image 986
Kris Avatar asked Sep 27 '12 11:09

Kris


2 Answers

Browsers will automatically select the first option unless you add the multiple attribute to the element.

See in you jQuery MultiSelect UI Widget javascript source file, They have implemented following

// browsers automatically select the first option
// by default with single selects
if( isSelected && !o.multiple ){
    labelClasses.push( 'ui-state-active' );
   }
like image 64
Miki Shah Avatar answered Sep 24 '22 20:09

Miki Shah


and you can always ensure that it works by looping through the elements and setting the value to not selected as well like:

  click: function(event, ui){

 if(!ui.checked) 
 {   $.each( $('#select2 option'),function(i2, element2)
       {
                if( $(element2).val() === ui.value )
                {
                   if( $(element2).is(':selected') ) { 
             $(element2).attr('selected',false); 
                }
                     $(element2).remove().appendTo('#select1');
                    }        
        });
 }

}

This is just in the event that you are updating dynamically and want to ensure that is so... in my case I was updating / passing over elements from one dropdown to another and both had the multiple='multiple' attribute so I needed to ensure that when clicking in one was being removed, then appending it to the underlying select but still the first option was always selected.. hope it helps someone down the road.. it's a nice plugin

like image 37
Jean G.T Avatar answered Sep 24 '22 20:09

Jean G.T