Laziale
Laziale

Reputation: 8225

knockoutjs conditionally set image src depending from a value

I want somehow to set the image source dynamically based on the name value I'm getting from js.

I tried something like this which works for setting the css class of specific div to make it working with image but its not working. What I want to achieve is the src to change dynamically depending from the name value

<img data-bind="attr:{src: 'image1.jpg' : Name == 'Package 1', src: 'image2.jpg' : Name == 'Package 2'}" />

For reference this is what is working for css styling:

<div data-bind="css: { package1_css: Name == 'Package 1', package2_css: Name == 'Package 2'" />

Upvotes: 1

Views: 1902

Answers (1)

ZeroBased_IX
ZeroBased_IX

Reputation: 2727

Use a computed observable for this.

self.ImageSource = ko.computed(function(){
    var url1 = "https://placeholdit.imgix.net/~text?txtsize=12&txt=101&50&w=50&h=50";
    var url2 = "https://placeholdit.imgix.net/~text?txtsize=12&txt=102&50&w=50&h=50";

    switch(self.Name()){
        case "Package 1":
            return url1;
        case "Package 2":
            return url2;
            break;
    }

}, self);

Also, bind to the image tag with the attr binding:

<img data-bind="attr: {src: ImageSource()}" />

Upvotes: 1

Related Questions