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?

7ochem
  • 7,532
  • 14
  • 51
  • 80
Bojjaiah
  • 3,992
  • 4
  • 56
  • 119
  • i use same approch for my knockout code if else condtion it not binding for my ul tag which contain 2 li.It adding extra line of div html tags enter image description here – Sara Jul 13 '18 at 11:12
  • https://tagvibe.com/magento2/how-to-set-if-else-and-conditions-in-knockout-js-magento-2/ – rajat kara Nov 29 '21 at 20:39

2 Answers2

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 -->
Suresh Chikani
  • 15,836
  • 11
  • 62
  • 99
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 -->
7ochem
  • 7,532
  • 14
  • 51
  • 80