0

I Have to add a dropdown dynamically on a button click. I'm trying to update the array but it is not showing the values in dropdown

<a data-bind='click:addBillItem'>Add</a>

My View Model is given below:

function AssignmentViewModel() {
self.billDescriptions = ko.observableArray();

this.addBillItem = function() {
            var = '<select id="ddlBillItemDescription" data-bind="';
            html += 'options:billDescriptions,';
            html += 'optionsText:"ItemName",';
            html += 'optionsCaption: "Select Bill Description",';
            html += 'optionsValue:"ItemName",';
            html += 'value:BillItemDescription';
            html += '</select>';
            $("#dropdown").append(html);
            self.billDescriptions(billItemDescriptions);
var billItemDescriptions = GetBillItemDescriptions();
self.billDescriptions(billItemDescriptions);
        };
}
ko.applyBindings(new AssignmentViewModel());
4
  • @Origineil I already have a ddlBillItemDescription dropdown on page load and bindings are applied to it. I want to bind the data to the dropdown that i added on button click Commented Aug 21, 2014 at 12:59
  • 1
    Applying bindings is how you bind data. If the html is not present in the DOM when you do so, you haven't bound it. See example Commented Aug 21, 2014 at 13:03
  • @Origineil Thanks, tried with your example but i'm getting an error like "You cannot apply bindings multiple times to the same element." Commented Aug 21, 2014 at 13:08
  • As is expected, if you click it more than once. Describe (in an edit to your post) what it is you are trying to achieve to clarify why you are approaching the problem this way. Either way, direct jQuery DOM manipulation is not the ideal "knockout" way, you can usually achieve a desired behavior strictly through a combination of bindings. Commented Aug 21, 2014 at 14:56

1 Answer 1

1

There are 2 options that I would recommend:

1) If you only need one of these dropdowns, put it in the markup with an if binding. Then, all you need to do is flip the flag bound to if to make your dropdown appear.

2) If you're going to make multiple dropdowns, setup a foreach binding in the markup, with the dropdown in the template (use the options binding). Then, in the viewmodel, have an array of objects representing the individual dropdowns (these are what will be bound to the options binding.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly the approach I was putting together, but had to go to a meeting :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.