Home > DeveloperSection > Forums > How to add and remove dynamic LI tag in UL tag using Knockout,js?
Pawan Shukla

Total Post:37

Points:267
Posted on    March-11-2015 2:00 AM

 JavaScript Knockout.js  Knockout mvc 
Ratings:


 1 Reply(s)
 654  View(s)
Rate this:

Hi I’m using knockout.js for add dynamic li tag

This is my code for add dynamic li tag:

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <script src="~/Scripts/knockout-2.0.0.js"></script>

</head>

<body>

    <h3>Employee List</h3>

 

    <form data-bind="submit: addEmployee">

        Employee List:

        <input data-bind="value: newEmployeeText" placeholder="Enter employee name" />

        <button type="submit">Add</button>

    </form>

 

    <ul data-bind="foreach: tasks, visible: tasks().length > 0">

        <li style="list-style: none">

            <input type="checkbox" data-bind="checked: isDone" />

            <input data-bind="value: title, disable: isDone" />

        </li>

    </ul>

    You have <b data-bind="text: EmployeeList().length">&nbsp;</b>

    <span data-bind="visible: EmployeeList().length == 0"></span>

    <script>

        function Task(data) {

            this.title = ko.observable(data.title);

            this.isDone = ko.observable(data.isDone);

        }

        function TaskListViewModel() {

            var self = this;

            self.tasks = ko.observableArray([]);

            self.newEmployeeText = ko.observable();

            self.EmployeeList = ko.computed(function () {

                return ko.utils.arrayFilter(self.tasks(), function (task) { return !task.isDone() });

            });

            self.addEmployee = function () {

                self.tasks.push(new Task({ title: this.newEmployeeText() }));

                self.newEmployeeText("");

            };

          

        }

        ko.applyBindings(new TaskListViewModel());

    </script>

</body>

</html>



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    March-11-2015 2:03 AM

First you need to add delete button inside loop.

<a href="#" data-bind="click: $parent.removeTask">Delete</a>

Now add this knockout code in your script tag

self.removeTask = function (task) { self.tasks.remove(task) };


Don't want to miss updates? Please click the below button!

Follow MindStick