Knockout binding to dynamically generated elements

I am using Knockout.js and I am pretty new to this. I created an example of my problem. Here I am trying to bind a knockout binding to dynamically generated elements. But snapping does not apply properly to dynamically generated elements.

I am trying to synchronize an input text field with a label element. Thus, no matter what we enter in the input field, the same text will be displayed in the corresponding label element. Please forgive me if I do not understand my question and please ask me for clearance. Help me guys? Thank you

+7
source share
1 answer

In your code, you are not using one of the main functions of knockout - html auto-generation. Instead of using jQuery to add a foreach binding and then use a string with observableArray . When you add a new element to the knockout of an array, you automatically generate html markup.

JavaScript:

 function CourseViewModel(){ var self = this; self.textValue = ko.observable(''); } function CeremonyViewModel() { var self = this; self.cources = ko.observableArray([new CourseViewModel()]); self.addCourse = function(){ self.cources.push(new CourseViewModel()); }; } ko.applyBindings(new CeremonyViewModel()); 

Html:

  <div id="menutab"> <form id="createMForm"> <input type="button" id="createmenu" value="Add menu" data-bind="click: addCourse"/> <div class="menu"> <table data-bind="foreach: cources" class="ui-widget ui-widget-content" > <tr> <td> <label for="CourseName">CourseName</label> </td> <td> <input type="text" data-bind="value: textValue, valueUpdate:'keyup'" class="CreateCourseName" name="CourseName" /> </td> </tr> </table> </div> </form> </div> <div id="courseoptiontab"> <form id="createCOForm"> <div class="options"> <table data-bind="foreach: cources" class="ui-widget ui-widget-content"> <tr> <td> <label class="colabel">Course Name <span class="forcourse" data-bind="text: textValue"></span> </label> </td> </tr> </table> </div> </form> <div> 

The fiddle works here: http://jsfiddle.net/vyshniakov/g5vxr/

+6
source

All Articles