Knokout select : Set Selected Item by item name no

2019-08-08 01:23发布

i have a knockout select as following

observable Array

issuingCountries

    0: 
       ObjectCoordinatorRegion: "EU"
       Country: "Australia"
       CountryId: 14
       Id: 1
   2: 
       ObjectCoordinatorRegion: "AU"
       Country: "Japan"
       CountryId: 16
       Id: 2

html

<select class="issuing_country" data-bind="options: issuingCountries,
                                           optionsText : 'Country',                               
                                           value:IssuingcountrySelected,
                                           optionsCaption:'---Select---',
                                         "
                        >
                        </select>

My question , i have { Country: "Japan" } in my hand,so how to set particular selected item as selected in dropdown.? so far i have tried

$('.issuing_country option[text="Japan"]').prop('selected', true); 

but failed ,let me know anyother way to do this. thanks

1条回答
狗以群分
2楼-- · 2019-08-08 02:26

You shouldn't be trying to set anything like that using jQuery when using knockout - instead, do it all on the viewmodel.

Your <select> options are bound to your issuingCountries observableArray, and the value selected is bound to your IssuingcountrySelected observable. To select an option automatically, just set the property on your viewmodel, and knockout will take care of the rest:

//Assuming "Japan" is at index 2:
vm.IssuingcountrySelected(vm.issuingCountries()[2]);

If all you know is the name of the option you want to select, first you must find the right item, so you'd need a function for that:

function findCountryByName(name) {
    for (var x = 0; x < vm.issuingCountries().length; x++) {
        if (vm.issuingCountries()[x].Country == name)
            return vm.issuingCountries()[x];
    }
    return null;
}
vm.IssuingcountrySelected(findCountryByName("Japan"));
查看更多
登录 后发表回答