Search code examples
c#jqueryasp.netknockout.jsknockout-3.0

Dynamically Add Rows in Knockoutjs


I am using knockoutjs and i have 2 column Qualification List and Marks . After clicking at Add button i want to generate new rows and after click on submit button it need to show the chosen Qualification List and my marks.

I have code here: https://jsfiddle.net/wg3t172b/

self.QualificationLists = ko.observableArray([
      { QualName: 'Master', QualId: '0' },
      { QualName: 'Bachelor', QualId: '1' },
      { QualName: 'CA', QualId: '2' },
      { QualName: 'School Leaving', QualId: '3' }
  ]);
  self.addQualification = function () {
      self.Qualifications.push({
         QualList: "",
         QualificationLists: "",
         Marks: "",
         selectedQualName: "",
    });
  };

  self.removeQual = function (Qualification) {
     self.Qualifications.remove(Qualification);
 };

  self.save = function (form) {
     console.log(self.Qualifications());
  };
};

var viewModel = new QualificationModel();
ko.applyBindings(viewModel);

when i console Qualification it shows only Marks but my expected result should be QualId QualName and Marks in one array.


Solution

  • To fix the scope for your select. Use $parent to move one scope out from the context inside your foreach binding.

    <select data-bind="options: $parent.QualificationLists, optionsText:'QualName',
    

    Edit: To clarify. When you are inside a foreach binding, your current scope is the current item in the iteration. Because your QualificationLists is directly on your viewmodel, and not actually on the items you are looping over, you have to call it from the parent context