开发者

Preselecting values in mulitselect with jQuery

I have a set of values that are present on the page loading: eg [1193,1184,2372].

I have a dropdownchecklist which can take a single value like so $(".ddl").dropdownchecklist().val(1193);

When I rebind the dropdownchecklist this selects the value correctly. However I've tried passing my array containing multiple values to the val() metho开发者_如何学编程d and that doesn't select the values. I kind of expected this. I'm not sure how to best go about preselecting.

I've tried iterating my array to build an filter attribute to apply as the following: $(".ddl [value*='1184'][value*='9067'][value*='14841']").attr('selected','selected');

but this doesn't work. I don't want to have to iterate all the options in the ddl and set them to selected if they match as there are hundreds of options and this won't be good performance wise, especially if there are only 2 options to be preseleted.

Any ideas?


Create a string of the selected ones to create the jQuery selector string and put it into the .find() function:

var str = '';
var arrLength = selectedArray.length;
$.each(selectedArray, function(i){
   str += 'option[value*='+selectedArray[i]+']';
   if((i+1) != arrLength){
     str += ', ';
   }
});

$('.ddl').find("option[value*='1184'], option[value*='9067'], option[value*='14841']")
     .attr('selected','selected'); 

Also note, when comparing a drop down with a value, you're looking for the option element in the select, not the select element itself.


I got it working with this but the above answer looks like a good solution:

$.each(arr, function(i,s)
{
     $(ddl_id + ' [value*=\'' + s + '\']').attr('selected','selected');
});    

Not sure which is likely to be faster but mines a little cleaner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜