Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data-bind value in jquery

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]

like image 995
user1926138 Avatar asked Aug 02 '13 14:08

user1926138


People also ask

How get data attribute value in jQuery?

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.

What is Bind method in jQuery?

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.

How do I find data attributes?

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.


1 Answers

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

like image 58
demkalkov Avatar answered Oct 04 '22 07:10

demkalkov