Search code examples
javascriptknockout.jsknockout-validation

Make one element visible depending on the value of another in knockout


I have three elements in my HTML, the Question, The Score, The Comment. The Score is an HTML SELECT, with "Poor", "Good" and "Excellent" as it's options.

I only want the Comment field to be visbile if the Score is not = "Good".

<!-- ko foreach: questions -->
  <tr>
      <td data-bind="text: question"></td>
      <td><select data-bind="options: availableScores"></select></td>
      <td>
         <!-- ko if: availableScores() != 'Good' -->
             <input data-bind="textInput: comment" />
         <!-- /ko -->
      </td>
  </tr>
 <!-- /ko -->

Any advice appreciated, thanks.


Solution

  • I assume that the comment textbox must only be visible if the selected score differs from the value 'Good'.

    For doing so, the selected value must be tracked and bound to the listbox, here below via the property selectedScore.

    A minimal MCVE shows this behaviour.

    var Question = function() {
    
      _self = this;
      _self.question = "";
      _self.comment = ko.observable("");
      _self.availableScores = ["Good", "Poor", "Excellent"];
      _self.selectedScore = ko.observable("Good");
    }
    
    var vm = new Question();
    ko.applyBindings(vm);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    
    <select data-bind="options: availableScores, value: selectedScore"></select>
      
    <!-- ko if: selectedScore() != 'Good' -->            
    Comment: <input data-bind="textInput: comment" />
    <!-- /ko -->