jquerydata-bindingkendo-uidynamic-bindingkendo-mvvm

Kendo ui: Cannot bind text value and button click event to viewModel for dynamically created HTML content


I am using Kendo MVVM and binding text field value and button click event to the viewModel using data attribute.

I can successfully bind the default value for the textbox and click event of the button that are initially rendered on the page.

But when I dynamically generate textbox and button, I am not able to bind the value and the click event to the viewModel.

Here is my working DEMO. Below is my code:

JS:

var viewModel = kendo.observable({
    textValue: 1,
    buttonClick: function(e) {
        alert("button click");
    },
  generateDynamicContent: function() {
    var html = '<input data-bind="value: dynamicTextValue" name="dynamicTextValue"/><input type="button" value="Dynamic Button" data-bind="click: dynamicButtonClick"/>';

        $('#dynamicContent').append(html);

  },
    dynamicTextValue: 2,
    dynamicButtonClick: function(e) {
        alert("dynamic button click");
    },
});
kendo.bind($("#example"), viewModel);

HTML:

<div id="example">
<input data-bind="value: textValue" name="textValue"/>
<input type="button" value="Button" data-bind="click: buttonClick"/>

<br />
<input type="button" value="Generate Dynamic Content" data-bind="click: generateDynamicContent"/>

<br/>
<div id="dynamicContent">
</div>

</div>

Solution

  • Try this code

    add kendo.bind($("#example"), viewModel); after appending html

    var viewModel = kendo.observable({
        textValue: 1,
        buttonClick: function(e) {
            alert("button click");
        },
      generateDynamicContent: function(e) {
        var html = '<input data-bind="value: dynamicTextValue" name="dynamicTextValue"/><input type="button" value="Dynamic Buttondddd" data-bind="click: dynamicButtonClick"/>';
    
        $('#example').append(html);
        //--------THIS LINE IS IMPORTANT
        kendo.bind($("#example"), viewModel);
      },
        dynamicTextValue: 2,
        dynamicButtonClick: function(e) {
            alert("dynamic button click");
        },
    });
    
    kendo.bind($("#example"), viewModel);
    

    DEMO