Activating knockout checkboxes based on interdependent conditions

Trying to create a checkbox enabling feature with dependencies.
The goal is to enable a checkbox if either of two input fields are not empty.
Check out the JavaScript code below:

var GoogleContactsViewModel = function() {
        var _self = this;
        _self.GoogleContacts = ko.observable();
        _self.IsEnabled = function (item) {
            console.log(item);
            return item.GivenName.length || item.FamilyName.length;
        };
        _self.GetData = function() {
            $.ajax({
                url: "some url",
                method: "POST",
                success:function (dataFromServer) {
                    _self.GoogleContacts(dataFromServer);
                }
            });
        };
        _self.GetData();
    };
    ko.applyBindings(new GoogleContactsViewModel());

Here's the HTML:

<table class="importContacts" data-bind="with: GoogleContacts">
    <thead>
        <tr>
            <th></th>
            <th>@CommonResource.LastNameColumn</th>
            <th>@CommonResource.NameColumn</th>
            <th>E-mail</th>
            <th>@CommonResource.MyEmployee</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: contacts">
        <tr>
            <td>
                <input type="checkbox" name="isImport" data-bind="value: FullName, enable: $root.IsEnabled($data)" />
            </td>
            <td>
                <input type="text" name="FamilyName" data-bind="value: FamilyName, valueUpdate: 'afterkeydown'" placeholder="@ContactResource.EnterLastName" />
            </td>
            <td>
                <input type="text" name="GivenName" data-bind="value: GivenName, valueUpdate: 'afterkeydown'" placeholder="@ContactResource.EnterName" />
            </td>
            <td>
                <span data-bind="text: Email"></span>
            </td>
            <td>
                <input type="checkbox" name="MyEmployee" value="" />
            </td>
        </tr>    
    </tbody>


</table>

It works perfectly for initializing.. View the printscreen here. However, it doesn't work with changes; meaning that after filling in any previously empty field, the checkbox does not enable.

Answer №1

To ensure updates are possible, utilize ko.observables in your data mapping process instead of creating a one-way binding.

In the function below, ko.mapping is used to convert received data into ko.observables and a computed function is added to each row of the data.

_self.GetData = function () {
    $.ajax({
        url: "some url",
        dataType: 'json',
        method: "POST",
        success: function (dataFromServer) {
            var localData = ko.mapping.fromJS(JSON.parse(contacts));
            var observArray = localData.contacts();
            for (var i = 0; i < observArray .length; i++) {
                observArray [i].IsEnabled = ko.computed({
                  read: function () {
                    console.log(this.GivenName());
                    return this.GivenName().length || 
                        this.FamilyName().length;
                },
                owner: observArray [i]
               });
              }

                _self.GoogleContacts(localData);
                ko.applyBindings(_self);
            },
            error: function (result) {}
        });
    };

Additionally, remember to include the ko enable binding on your checkbox.

<td>
     <input type="checkbox" name="MyEmployee" value="" 
            data-bind="enable: IsEnabled " />
</td>

UPDATE - Revised GetData to be compatible with the JSFIDDLE code snippet provided below.

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

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

utilizing the dropdown label for validating the value of another dropdown

I'm facing a challenge with two dropdowns: <select name="first_value" id="first_value"> <option value="<?php print"$sum_jan" ?>">January</option> <option value="<?php print"$sum_feb" ?>">February</option ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

Is a JavaScript variable automatically global if not declared with var?

Here is the code snippet from one of my files: function refreshGridSuccess(responseText, entity) { oTable = $('#dataTable').dataTable({ "sScrollX": "100%", In a different file, I have the following code: $('#d ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Please provide a code for the conversion of Excel data into JSON format

I'm curious to learn how one can convert data from an Excel spreadsheet into JSON format using JavaScript. Specifically, I have a file named task.xlsx located at C:\rex\task.xlsx. Any guidance on this would be greatly appreciated! Thank you. ...

Exploring deeply nested arrays in objects to locate matching elements

In my current array, there are multiple objects, each containing an array property. The array within each object holds different genres associated with a movie. const films = [ { name: 'Ant-Man and the Wasp', genre: ['Action&apo ...

Avoiding repeated execution of a JavaScript function

Using JavaScript, jQuery, and PHP, how can I ensure that a JavaScript function is only executed once? In my MainJQuery file, the Ajax request to display.php runs for a period of time: .... $.ajax({ type:'POST', url: 'display.php&a ...

Performing queries using the ORM Sequelize to fetch data from two separate tables simultaneously during a single page

I have encountered a challenge while working on my project. I need to display data from two different tables on one page (page.hbs). My tech stack includes Node.js ORM Sequelize, MySQL database, and Handlebars for templating. However, I am facing difficult ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Steps to show a message on screen for a duration of 3 seconds using JavaScript

setTimeout(function(){ document.getElementById("alarmmsg").innerHTML=msg; },3000); The code above is successfully displaying the message but it's not going off the screen as expected. What might be causing this issue? ...

Is there a way to assign classes to elements within a sequence based on their index positions?

My goal is to create a list with alternating classes that have a start and end class for each set of items. For example, I currently have the following code: <div class="wrap"> <div class="item-a"></div> <div cl ...

Encountering an issue - Unable to define 'headers'

I've encountered an error that says "Can't set Headers of Undefined." Here is the code snippet causing the issue: Separately defined headers: var headers = function (req,res,next){ res.setHeader("Access-Control-Allow-Origin", "[*]"); re ...

Shadows with pixel art style in Threejs

I developed an application where I dynamically created shelves. Everything is working fine except for the shadows. I'm not sure if the issue lies with the lighting or the objects themselves. Can anyone provide some assistance? Here is a snapshot showc ...

Is there a way to simulate a right-click using node.js selenium-webdriver?

Currently, I am utilizing selenium-webdriver for Node.js. I am trying to simulate a right-click using this driver. However, I have searched through the official documentation and cannot find any information on how to do this. Can anyone provide guidance o ...

What is the best way to hide a div containing a ul list when all <li> elements within it have the display property set to none

Having an issue with my search feature. I have 6 different categories as shown below. When searching for something, I want the category box with no results to be hidden - all li elements should have display: none properties. <div class="category"> ...

In what ways can we enhance the appearance of the show entries and make the font in Datatables larger?

Working on an HTML file that contains mainly tabular data. Utilized the styling features of Datatables, but looking to customize the color, border color, and size of the select icon next to the show entries option along with increasing the text. The German ...

Parsing and Displaying JSON Data from a Python DataFrame in D3

Trying to create a stock chart, I encountered an issue with parsing the json file output by my python dataframe. The example code from http://bl.ocks.org/mbostock/3884955 does not seem to fit the format of my data: The json looks like this: var dataset = ...

How can I extract several values from a child component in React?

Is there a way to retrieve two values in a single method of the Parent Component by passing props value from Child Component? What would be the best approach? Form.js (Child Component) // First method -> Extracting the suggestion value and passing i ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...