How to have multiple data-bind attributes on one element?

JavascriptJqueryknockout.js

Javascript Problem Overview


I need to have multiple data bindings on one element. For example, I want a href as well as a html data-binding on one a tag. I have tried this,

<a data-bind="html: name" 
   data-bind="attr: { href: url }" 
   data-bind="attr: { 'data-prop': xyz }">
</a>

But this doesn't work. It seems knockout only supports binding one data-bind property? How to bind both the href, the inner html, and a custom "data-prop" attribute on one element?

Javascript Solutions


Solution 1 - Javascript

Like this:

<a data-bind="html: name, attr: { href: url }">

You use comma-separated bindings - the attribute is the same as passing an object:

{
    html: name, 
    attr: { href: url }
}

Or, if you're asking about multiple attr bindings at once:

<a data-bind="html: name, attr: { href: url, 'data-prop': FullName }">

Solution 2 - Javascript

This is how I implemented the source attribute and click event using data-bind. You may find it useful.

<img data-bind="{click: function(data, event) {ESVendorWidget.loadFunction(data,event)},
                 attr: {src: $data.Photo.PhotoUrl }}"
     alt="package pic" class="big" />

Solution 3 - Javascript

I simply use:

<input type="checkbox"
    data-bind="click: callFunction(), checkedValue: 0, checked: Card.Days">

for a checkbox element.

Solution 4 - Javascript

you can use multiple properties using , like below

<a data-bind="attr: { href: url, id: id , class: classvalue}">

object like this

{ url: 'http://stackoverflow.com', id:'newid' , classvalue: 'classname' }

Solution 5 - Javascript

you can use like below

> data-bind="text: method.method_title, attr: {'id': 'label_method_' + > method.method_code}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionImran Qadir Baksh - BalochView Question on Stackoverflow
Solution 1 - Javascriptpaulslater19View Answer on Stackoverflow
Solution 2 - Javascriptaamir sajjadView Answer on Stackoverflow
Solution 3 - JavascriptchrisView Answer on Stackoverflow
Solution 4 - JavascriptSurendra Kumar AhirView Answer on Stackoverflow
Solution 5 - JavascriptGohil RajeshView Answer on Stackoverflow