Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8440063
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T08:10:56+00:00 2026-06-10T08:10:56+00:00

I’m using KnockOutJS – I have a basic JSON model: ([{ occ: [{name: 1

  • 0

I’m using KnockOutJS – I have a basic JSON model:

([{
    "occ": [{"name": "1 Room only","price": 53.9},
            {"name": "1 B&B","price": 62.16},],
    "TypeName": "Single",
    "TypeID": "3121",
    "TypeCount": "5"
   },
{
    "occ": [{"name": "2 B&B","price": 24.23},
            {"name": "2 DBB","price": 32.95}],
    "TypeName": "Double",
    "TypeID": "4056",
    "TypeCount": "4"
   }])

The idea is, TypeName holds the type of room available – eg. Single, Double – and TypeCount, holds the number of that room available.

Using KnockOut, and a lot of help from this forum, the current JSFiddle code creates a Cart type example – where you can add rooms, and select how many of that type of room you would like.

However, if the user selects “Single“, and selects 4 from the quantity (meaning there is only 1 Single Room remaining), and then clicks Add Room, and again, selects TypeName “Single”, I would like KnockOut to be able to have kept a track of previous lines having “Single” chosen, and the quantity chosen – and therefore know that the user can only select 1 from the quantity, when adding a Single room again.

Sort of keeping a running total – so it knows what’s been selected on the screen, and can relate that back to the TypeCount in the JSON for each TypeName.

This is similar to the custom bindings tutorial on KnockOuts site: KnockOut Custom Bindings Example

I’ve created many forks in JSFiddle, but can’t get it to do what I want – the last working example is: Link to JSFiddle example

Thank you for any pointers/help,

Mark

The HTML is

<div class='liveExample'> 

<table width='100%' border="1">
    <thead>
        <tr>
            <th width='25%'>Room Type</th>
                <th width='25%'>Occ</th>
            <th class='price' width='15%'>Price</th>
            <th class='quantity' width='10%'>Quantity</th>
            <th class='price' width='15%'>Subtotal</th>
            <th width='10%'> </th>
        </tr>
    </thead>
    <tbody data-bind='foreach: lines'>
        <tr>
            <td>
                <select data-bind='options: $root.RoomCategories, optionsText: "TypeName", optionsCaption: "Select...", value: category'> </select>
            </td>
            <td data-bind="with: category">
                <select data-bind='options: occ, optionsText: "name", optionsCaption: "Select...", value: $parent.product'> </select>
            </td>
            <td class='price' data-bind='with: product'>

<span data-bind='text: formatCurrency(price)'> </span>
            </td>
            <td class='quantity' data-bind="with: category">
                <select data-bind="visible: $parent.product, options: ko.utils.range(0, TypeCount), value: $parent.quantity"></select>
            </td>
            <td class='price'>
                <span data-bind='visible: product, text: formatCurrency(subtotal())' > </span>
            </td>
            <td>
                <a href='#' data-bind='click: $parent.removeLine'>Remove</a>
            </td>
        </tr>
    </tbody>
</table>
<p class='grandTotal'>
    Total value: <span data-bind='text: formatCurrency(grandTotal())'> </span>
</p>
<button data-bind='click: addLine'>Add room</button>
<button data-bind='click: save'>Submit booking</button>

and the KnockOut code is

function formatCurrency(value) {
return "$" + value.toFixed(2);
}

var CartLine = function() {
var self = this;
self.category = ko.observable();
self.categoryID = ko.observable();
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function() {
    return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
});

// Whenever the category changes, reset the product selection
self.category.subscribe(function() {
    self.product(undefined);
});
};

var Cart = function() {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;

self.RoomCategories = ko.observableArray([]);
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
self.grandTotal = ko.computed(function() {
    var total = 0;
    $.each(self.lines(), function() {
        total += this.subtotal()
    })
    return total;
});

// Operations
self.addLine = function() {
    self.lines.push(new CartLine())
};
self.removeLine = function(line) {
    self.lines.remove(line)
};
self.save = function() {
    var dataToSave = $.map(self.lines(), function(line) {
        return line.product() ? {
            category: line.category().TypeName,
            categoryID: line.category().TypeID,
            productName: line.product().name,
            quantity: line.quantity()
        } : undefined
    });
    alert("Could now send this to server: " + JSON.stringify(dataToSave));
    };
};

var cart = new Cart();

ko.applyBindings(cart);

//simulate AJAX
setTimeout(function() {
cart.RoomCategories([{
    "occ": [{
        "name": "1 Room only",
        "price": 53.9},
    {
        "name": "1 B&B",
        "price": 62.16}, ],
    "TypeName": "Single",
    "TypeID": "3121",
    "TypeCount": "2"


    },
{
    "occ": [{
        "name": "2 B&B",
        "price": 24.23},
    {
        "name": "2 DBB",
        "price": 32.95}],
    "TypeName": "Double",
    "TypeID": "4056",
    "TypeCount": "2"


    },
{
    "occ": [{
        "name": "2+1 BB",
        "price": 34.25},
    {
        "name": "2+1 DBB",
        "price": 36.23}],
    "TypeName": "Family",
    "TypeID": "5654",
    "TypeCount": "4"}]);
}, 100);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T08:10:58+00:00Added an answer on June 10, 2026 at 8:10 am

    Essentially you’re asking knockout to do too much logical work when you should be using native javascript by storing your running total in a JS object and using JS to run the calculations. The example I’ll give isn’t plug & play into your code, but it’s relevant.

    First, store room counts in an object.

    roomcount = { // object can be accessed by any other variable in your app
        single: 5, // data from json or where ever
        double: 4
    }
    

    Then, your KO viewmodel would work something like this

    self.showAvailableSingle = ko.ovservable(roomcount.single) // Show available rooms to user
    self.showAvailableDouble = ko.ovservable(roomcount.double)
    self.selectSingleQuantity = ko.observable(""); // user input number of rooms
    self.selectDoubleQuantity = ko.observable("");
    
    self.selectSingleQuantity = function() { // click event
        roomcount.single = roomcount.single - self.selectSingleQuantity();
        self.showAvailableSingle(roomcount.single); // this will update what is shown to the user
    }
    
    self.selectDoubleQuantity = function() { // click event
        roomcount.Double = roomcount.Double - self.selectDoubleQuantity();
        self.showAvailableDouble(roomcount.Double);
    }
    

    Like I said, this will need to be modified to work with your code, but hopefully it’s an example that will send you down the right path. This general idea can be used to update select input options or other fancier things.

    The other reason you want to use KO as little as possible for the computational and logical aspects of your app is because your final KO view model will be large and annoying to parse your necessary data. It’s important to try and use KO only for the view model, and not logic.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have thousands of HTML files to process using Groovy/Java and I need to
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a jquery bug and I've been looking for hours now, I can't
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.