Jürgen
Jürgen

Reputation: 27

Take string from data-bind inside a link

I am new to JavaScript and I am having this issue. Maybe I am asking something very dumb but I can't find a solution.

I have this:

<div class="text" id="title" data-bind=" text:display >
</div> 

I need to take the string from data-bind, replace the spaces for a + symbol and and put it inside a link.

I need something like this:

<a href="path/index.php=q?%22 "Here the string" %22 " target="iframe2">click</a>

So like this I end up creating a search link with the value of data bind. Also I need to target iframe2 because my site is divided into two iframes.

I hope somebody can help me. Thanks!

Upvotes: 1

Views: 316

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

Considering you're using knockout, why not use the attr binding?

<a data-bind="attr:{href:'path/index.php?q='+encodeURIComponent(display())}">click</a>

Another option is to provide your own bindingHandler:

ko.bindingHandlers.customLink = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext){
        var val = ko.unwrap(valueAccessor());
        element.href = 'index.php?q=' + encodeURIComponent(val);
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext){
        var val = ko.unwrap(valueAccessor());
        element.href = 'index.php?q=' + encodeURIComponent(val);
    }
};

Then you'd use:

<a data-bind="customLink:display">click</a>

Upvotes: 2

Related Questions