11

I am customizing the shopping cart page, Here I worked knockout js and html code file. I successfully wrote If statement by below code.

<!-- ko if: isFreeShipping() -->
   //My Code goes here
<!-- /ko -->

For else statement not working, for these, I wrote below code.

    <!-- ko if: isFreeShipping() -->
       //My Code goes here
    <!-- ko ifnot: isFreeShipping() -->
       //My Code goes here
    <!-- /ko -->

Error: Uncaught Error: You cannot apply bindings multiple times to the same element.

Can you please suggest me how to write If Else statement in html file?

2

2 Answers 2

21

You should write a below code for else condition

<!-- ko if: isFreeShipping() -->
    //My Code goes here
<!-- /ko -->
<!-- ko ifnot: isFreeShipping() -->
    //My Code goes here
<!-- /ko -->
2
  • 1
    Thankq. It's worked like charm!......
    – Bojjaiah
    Commented Mar 8, 2018 at 10:50
  • 2
    So the OP forgot the first <!-- /ko -->...
    – 7ochem
    Commented Apr 6, 2018 at 12:28
7

Just to extend a bit on Suresh Chikani's answer to include more combinations under this question:

To do a if-elseif-else construction you would have in PHP:

if (A && B) {
    //...code
} elseif (A) { // And thus 'not B'
    //...code
} else { // Thus is 'not A' and 'not B'
    //...code
}

In Knockout you would do:

<!-- ko if: A && B -->
    //...code
<!-- /ko -->
<!-- ko if: A && !B -->
    //...code
<!-- /ko -->
<!-- ko if: !A && !B -->
    //...code
<!-- /ko -->
2
  • what about if($value == "random value")
    – Asad Khan
    Commented May 11, 2022 at 8:02
  • I don't understand your comment. Maybe it is better to ask a new question if this what you are saying is different from an if-else construction like the OP is asking about or an if-elseif-else construction I'm talking about.
    – 7ochem
    Commented May 12, 2022 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.