Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit or credit simultaneously, I need help to display the amount under the appropriate category – credit or debit. Here's a snippet of the viewmodel:

 function JournalViewModel() {
var self = this;
self.Period = ko.observable();
self.PayGroup = ko.observable();
self.PayGroups = ko.observableArray([]);

// Load periods using AJAX
self.LoadPeriods = function () {

    $.ajax({

        url: baseUrl + 'api/Process/Load',
        type: 'GET',
        headers: { 'Access-Control-Allow-Origin': '*' },
        dataType: 'json',
        success: function (data) {
            console.log(data);
            if (data.Successfull == 1) {
                self.Period(data.Model.CurrentPeriod);
                self.PayGroups(data.Model.Paygroups);
            }

        },
        error: function (request, error) {
            console.log(error);
        }
    });
}

self.periodId = ko.observable();
self.PaygroupId = ko.observable();
self.Journal = ko.observableArray([]);
self.PayMaster = ko.observableArray();

// Load journal data using AJAX
self.LoadJournal = function () {

    $.ajax({

        url: baseUrl + 'api/Journal/LoadJournal/'+periodId +'/'+self.PaygroupId(),
        type: 'GET',
        cache: false,
        headers: { 'Access-Control-Allow-Origin': '*' },
        dataType: 'json',
        success: function (data) {              
            if (data.HasError == 0) {
                self.Journal(data.Model);
                console.log(data.Model);
                alert("Journal Successfully Processed");
                $("#listTable").DataTable();

            }

        },
        error: function (request, error) {
            console.log(error);
        }
    });
}

self.StartDate = ko.observable()
self.EndDate = ko.observable()
self.NbDays = ko.observable();
self.NbHours = ko.observable();
self.Code = ko.observable();
self.CountEmployees = ko.observable();
self.LoadPeriods();
}
ko.applyBindings(new JournalViewModel());

This is my view:

  @{
    ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
  <nav role="navigation" aria-labelledby="system-breadcrumb">
 <ol class="breadcrumb">
    <li><a href="#">Process</a></li>
    <li><a href="#">Journals</a></li>
 </ol>
 </nav>
  <div class="box box-primary">
  <div class="box-body">
    <div class="col-md-12">
        <div class="col-md-2">
             <div class="form-group">
                <label for="PeriodTxt">Pay Group</label>
                <select data-bind="options: PayGroups,
                    optionsText: 'Name',
                    optionsValue: 'Id',
                    optionsCaption: 'Choose...',
                    value:PaygroupId" class="form-control"></select>
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="PeriodTxt">Period</label>
                <input id="FullNameTxt" class="form-control" type="text" 
   readonly="readonly"
                       data-bind="value:Period()?Period().Code:''" />
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="StatusTxt">Number of Hours</label>
                <input id="StatusTxt" class="form-control" type="text" 
 readonly="readonly"
                       data-bind="value:Period()?Period().NbHours:''" />
            </div>
        </div>
        <div class="col-md-2">
            <div class="form-group">
                <label for="ds"></label>
                <input type="submit" value="Load Journal" data-
  bind="click:LoadJournal" class="btn btn-primary btn-block" />
            </div>
        </div>
    </div>
 </div>
 </div>
  <div class="well">
   <div class="well-body">
    <table id="listTable" class='table table-striped table-bordered'>
        <thead>
            <tr>
                <th>
                    Account Code
                </th>
                <th>
                    Name
                </th>
                <th>
                    Debit
                </th>
                <th>
                    Credit
                </th>

            </tr>
        </thead>
        <tbody data-bind="foreach:Journal">             
                <tr>
                    <td data-bind="text:AcctId">                            
                    </td>
                    <td data-bind="text:AcctDescription">                           
                    </td>
                    <!-- ko if:Debit==1 -->
                    <td data-bind="text:Amount">                        
                    </td>
                    <!-- /ko -->
                    <!-- ko if:Credit==1 -->
                    <td data-bind="text:Amount"></td>
                    <!-- /ko -->                                                                
 </tr>

        </tbody>
    </table>
</div>
 </div>
 @section Scripts{
 <script>periodId = '@ViewBag.PeriodId';</script>
 }

Answer №1

The issue lies in having the if condition on the span tag, which means it will not display if false. To ensure the span tag is displayed at all times but only hide the value inside based on conditions, you should place the if condition inside the span tag. (Assuming I have correctly understood your question)

<table>
  <thead>
    <tr>
      <th>Account Code</th>
      <th>Name</th>
      <th>Debit</th>
      <th>Credit</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td data-bind="text:AcctId"></td>
      <td data-bind="text:AcctDescription"></td>
      <td>
        <span data-bind="if: Debit == 1">
          <!-- ko text: Amount -->
          <!-- /ko -->
        </span>
      </td>
      <td>
        <span data-bind="if: Credit == 1">
          <!-- ko text: Amount -->
          <!-- /ko -->
        </span>
      </td>
    </tr>
  </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...

Combine the information from 3 separate subscriptions into a single object using RxJS in Angular 9

I am seeking assistance with merging data from 3 different sensors into one object. I am using Cordova plugins to retrieve accelerometer, gyroscope, and magnetometer data. However, I am facing an issue in subscribing to all three observables simultaneously ...

Choosing elements in jQuery

Having some trouble with the subnav on my current website project. I think the issue lies in how I am selecting items in my jquery code. It seems like a small fix that needs to be made, but I'm unsure of the correct approach. http://jsfiddle.net/ZDEr ...

populating a multi-dimensional array using a "for" loop in Javascript

It appears that JavaScript is attempting to optimize code, causing unexpected behavior when filling a multidimensional array (largeArr) with changing values from a one-dimensional array (smallArr) within a loop. Take the following code for example: largeA ...

Error: Unable to call topFrame.window.changeSelectedBarStyle because it is not a valid function. What could be causing this

This function is called changeSelectedBarStyle: function changeSelectedBarStyle(tdId){ $("#menuTable td").each(function(index){ if(this.id == tdId){ $(this).removeClass("menuPanel"); $(this).addClass("menuPanelSelected" ...

What is the purpose of the "Dot" symbol in the "runtimeArgs" property of the launch.json file in Visual Studio Code?

As I opened my Visual Studio Code today, a notification greeted me about a new update. Without hesitation, I went ahead and installed it, assuming it would be like any other update I've had in the past. However, after updating to version 1.22.1, I enc ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Enhancing functionality by updating a function to accept an object as input instead of individual key:value pairs in TypeScript

I'm currently tackling a challenge with a friend's icon library component, specifically with their set() function. The issue arises when I want to invoke two functions, namely setRandomColor() and setColor(), both intended to update two values w ...

The AnchorEL component becomes unusable once a function has been executed for the first time

I am facing a challenge with anchorRef and struggling to understand how it works as I am new to React and have never used it before. After the onClickAway method is called, Material-UI shows an error stating that the anchorRef is set to null, but this warn ...

Determining if the device orientation matches the given coordinates through a logical process

Exploring the capabilities of browser API's related to geolocation and device orientation. I'm wondering, if I have information on someone's orientation (like a compass angle from 0 to 360 degrees), is it feasible to determine if they are f ...

Unexpected outcomes arise when parsing headers from a file-based stream

Currently, I am in the process of creating a small parser to analyze some log files using node streams (more specifically io.js). I have been referring to the documentation for unshift to extract the header. While I can successfully divide the buffer and ...

Issue with external JavaScript file being unresponsive on mobile browser

Hello everyone, hope you're having a great afternoon or evening I've encountered an issue with mobile browsers like Chrome Mobile and Kiwi where the external js file is not visible in the html file. The script.js file looks like this: alert(&ap ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Enhance Your Browsing Experience with this Chrome Extension for Page Interactions

Recently, I came across Chrome extensions and have been intrigued by their functionality. One question that has been on my mind is: how can I programmatically trigger a button click when the extension runs? For instance, there is a button with the id &apos ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

Sending a file using Angular's $http service

I am facing an issue while trying to upload a form with an image file using the angular $http function and multer in the background for receiving. I have successfully uploaded the image via a direct form submission (without angular) as shown below: <fo ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...