I have a dropdown with list of values loaded using dwr call. I fetch data from db say I have a location called India. I use

$('select[name="cname"]').find(
'option:contains("'
+ data.loc + '")')
.attr("selected", true);

to make it selected. cname is the dropdown name. data.loc is the data i fetch from db. The problem here is if i have two locations like India and Indiana, it iterates and set both values as selected with the recent value(Indiana) being set. The actual value to be set is India. Only if i select Indiana it has to be selected and not for India. Is there any option to fix this?

有帮助吗?

解决方案

You can use filter() to apply the custom filter match the elements return by selector.

$('select[name="cname"] option').filter(function(){
    return $(this).text() == data.loc; 
}).attr("selected", true);

其他提示

why don't you use val()

$('select[name="cname"]').val(data.loc)

Use Equals Selecter.Please refer this

Why not a check for the equality:

if($(this).val() == data.loc){
    $('select[name="cname"] option[value="' + data.loc + '"]').attr("selected", "selected");
}

you can done it by Val(), Try like below it will help you..

$('select[name="cname"]').val(data.loc);
alert($("select[name='cname'] option:selected").text());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top