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
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' );
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With