Вопрос

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