Reputation: 822
I have a data-bind with input textbox
<input id="tColorCode" type="text" data-bind="value: ColorCode" />
I don't have access to the external JavaScript where the view model is setup so I don't have information I need about the object but if I click an element then in the handler I can change it's value:
$("#tColorCode").live("click", function () {
//....
ko.dataFor(this).ColorCode("#ffffff");
}
But I need to do that outside of the click handler and so I try with the element's name but it does not work:
var c = $("#tColorCode");
console.log(c); //OK
ko.dataFor(c).ColorCode("#ffffff"); //TypeError: ko.dataFor(...) is undefined
Can this be done another way?
Thank you!
Upvotes: 4
Views: 9256
Reputation: 24901
You need to pass specific HTML element to method dataFor
, however, variable c
is jQuery selector, not an element.To get specific element from a selector you can simply get the first item of a selector:
var c = $("#tColorCode");
ko.dataFor(c[0]).ColorCode("#ffffff"); // use c[0] instead of c
The difference from the event handler case, is that in event hander this
represents a specific element, not a selector, so it was working correctly.
Upvotes: 6