Here’s the relevant code:
<div data-bind="foreach: chats, visible: chats().length > 0">
<input data-bind='value: $parent.newCommentText' />
<a href="#" data-bind='click: $root.addComment'>Add comment</a>
</div>
ViewModel:
self.newCommentText = ko.observable()
self.addComment = function(chat) {
var newComment = { CourseItemDescription: self.newCommentText(), };
chat.CommentList.push(newComment);
self.newCommentText("");
$.ajax({
url: "@Url.Action("AddComment")",
data: ko.toJSON(newComment),
type: "post",
contentType: "application/json"
});
};
The problem is that this will put whatever I type in one text box in all the other text boxes. How can I make it so that it only binds to the textbox that the user is typing in and have that data available to the addComment function?
If you want each chat to be able to have their own comment field to add, then you would want to add your
newCommentTextfield to thechatobject rather than the parent. Then you can read it and clear it out off of thechatobject that is passed toaddComment.