I am using knockout js to set a span value.
HTML Code
<span id="spnQStreamChat" data-bind="text: $data.OnLineUserName"></span>
this is working fine and showing user name on the UI.
I am trying to get that value from js file. by using below code
alert($(this).attr('data-bind'));
this is serving result like this text: $data.OnLineUserName . I want the username assigned by me.
In UI its showing Bhagirathi but in js its showing the content present in the data-bind
how to get the Name(means: Bhagirathi) in js file
please help to solve this problem
thanks in advance
[EDIT]
$(document).on("click", ".btn-mini", function (e) {
alert(ko.contextFor($('.btn-mini')[0]).$data.OnLineUserName);
try {
var connectionId = chatHub.server.getUserConnectionId($(this).attr('data-bind').username, sessionUserName);
}
catch (e) {
//error
}
});
[/EDIT]
You can use this jquery attr() syntax for get data-id attribute value. $("selector"). data("data-textval"); You can use this jquery attr() syntax for get data-textval attribute value.
jQuery bind() Method The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
You can get the knockout context for element with
ko.contextFor($('#spnQStreamChat').get(0))
this will return an an object like
ko.bindingContext {$parents: Array[1], $root: ViewModel, ko: Object, $data: SomeObject, $parentContext: ko.bindingContext…}
where $data is your $data object. So to get the name you need something like
ko.contextFor($('.button.btn.c_btn').get(0)).$data.OnLineUserName()
This way is more useful when you need to get $data object. Otherwise you can just get the 'text' of a span with jQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With