Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a text link in a Knockout javascript table?

I've got some KnockoutJS code working - it pulls in a list and binds it to a table.

For the table-data which displays the name, I would like that to be an <a href=...>, but not sure how. The name is still displayed. But you can click on it.

Here's my current code:

<tbody data-bind="foreach: items">
    <tr>
        <td data-bind="text: name()"></td>
        <td data-bind="text: price()"></td>
        <td data-bind="text: endsOn()"></td>
    </tr>   
</tbody>

nothing too crazy.

I have another property called url which contains the full http://blah URL to direct the users to. Also, I would like a new tab to open up.

Any suggestions?

like image 871
Pure.Krome Avatar asked Dec 12 '12 13:12

Pure.Krome


People also ask

How does knockout work in JavaScript?

Knockout sets the element’s content to a text node with your parameter value. Any previous content will be overwritten. If this parameter is an observable value, the binding will update the element’s text whenever the value changes. If the parameter isn’t observable, it will only set the element’s text once and will not update it again later.

How to create a link in JavaScript?

How to create a link in JavaScript ? Given an HTML document and the task is to create a JavaScript link and add it to the document using JavaScript. Create an anchor <a> element. Create a text node with some text which will display as a link. Append the text node to the anchor <a> element. Set the title and href property of the <a> element.

How do I add a link to a node in HTML?

Approach: 1 Create an anchor <a> element. 2 Create a text node with some text which will display as a link. 3 Append the text node to the anchor <a> element. 4 Set the title and href property of the <a> element. 5 Append <a> element in the body.

How to anchor a link using JavaScript?

+ "a link using JavaScript."; // Create anchor element. // Create the text node for anchor element. // Append the text node to anchor element. // Set the title.


1 Answers

You have to remove data-bind attribute from td tag and put a with attr binding inside td:

<tbody data-bind="foreach: items">
    <tr>
        <td><a data-bind="text: name, attr: {href: url}" target="_new"></a></td>
        <td data-bind="text: price"></td>
        <td data-bind="text: endsOn"></td>
    </tr>   
</tbody>

P.S. You don't have to put () after property name in data-bind attribute if you don't construct expression.

like image 120
Artem Vyshniakov Avatar answered Oct 19 '22 03:10

Artem Vyshniakov