XAF
XAF

Reputation: 1472

knockout js selected option

I have a select tag in my html with knockout js binding.

<select class="form-control " data-bind="options: loanTimesBorrower,
   optionsText: loanTimesBorrower(),
   value: loanTimeBorrower,
   selectedOptions: loanTimesBorrowerini,
   optionsCaption: 'Choose dates'">
</select>

Instead of choose date I want to show the default value as 180, since I have a array which stores this loantime as 180 days, 360 days etc.

this is the array

self.loanTimesBorrower = ko.observableArray();
self.loanTimesBorrowerini = ko.observableArray(self.loanTimesBorrower()[0]);

and I get this array populated by a foreach loop which is getting the loantimes from db like this.

$.each(items.investTimes, function (index, item) {
  self.loanTimesBorrower.push(item.Loantime);
});

So I am not sure how the default value can be put as 180 instead of choose dates

Upvotes: 0

Views: 1050

Answers (2)

Masnad Nihit
Masnad Nihit

Reputation: 1996

Remove optionsCaption: 'Choose dates' It would default to the option you provided.

Upvotes: 1

Dipiks
Dipiks

Reputation: 3928

You can use it like this:

<select id="selectDate" class="form-control " data-bind="options: loanTimesBorrower,
   optionsText: loanTimesBorrower(),
   value: loanTimeBorrower,
   selectedOptions: loanTimeBorrower[0],
   optionsAfterRender: $root.setDefaultDate">
</select>

And in your javascript you can do something like:

    self.setDefaultDate= function (option, object) {
        if (typeof object !== "undefined" && object !== null) {
            if(object.value === 180) {
                $("#selectDate").find(option).prop('selected', true);
            }
        }
    };

if you show me what the object in your array looks like I can edit the answer for a better fit. But that should help you to find your way

Upvotes: 0

Related Questions