Creating a shared observable array in KnockoutJs to be used for multiple select elements

When an employer needs to assign a specific employee and premium amount, they can click on the "Add Employee" button to reveal another form with a dropdown menu of employees and an input field for the premium amount.

<select>
    <option>John</option>
    <option>George</option>...
</select>

<input type="text" placeholder="Amount"/>

I am using a shared ko.observableArray to manage dynamically added select boxes and inputs, which is functioning properly...

An issue arises when the employer selects the same employee more than once (which is not ideal). I attempted to create a new array using ko.computed that would filter out previously selected employees, but so far without success.

Ideally, a selected option should be disabled or hidden from other dropdown menus.

Has anyone successfully addressed this issue before?

Answer №1

After encountering a problem, I managed to find a solution in the following way:

To start off, I had to make some changes by replacing my

<selec data-bind="options: employyes">....

with a foreach loop and manually rendering my items like this:

<select data-bind="value: selectedEmployee, foreach: $root.employees, click: $root.updateEmployees, optionsAfterRender: $root.updateEmployees">
    <option value selected="selected" data-bind="visible: $index === 0">Choose...</option>
    <option data-bind="value: id, text: name, attr: {'disabled': disabled}"></option>
</select>

Subsequently, I created a function that updates the state of Employees every time a user clicks on the select element... This function loops through all employees and checks if an employee ID is selected in any form. If it is, the disable attribute is set to true; otherwise, it's set to false.

self.updateEmployees = function() {
        ko.utils.arrayForEach(self.employees(), function (employee) {
            var isEmployeeUsed = false;
            ko.utils.arrayForEach(self.forms(), function (form) {
                console.log(employee.id());
                if (typeof employee !== 'undefined' && typeof form !== 'undefined' && employee.id() === form.selectedEmployee()) {
                    isEmployeeUsed = true;
                }
            });

            employee.disabled(isEmployeeUsed);    
        });

Check out the JS Fiddle for this solution

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

Serve static assets files based on the route path instead of using absolute paths

Within Express, I have set up the following route: app.get('/story/:username', function(req, res){ res.render('dashboard.ejs'); }); Prior to that, I am serving any static files located in /public: app.use(express.static(__dirname ...

What could be causing my cmd to report an error stating that it is unable to locate the node-modules

https://i.sstatic.net/4ztfB.png Take a look at my command prompt below. Do I need to keep the module folder and the code folder in the same directory? ...

What are the best ways to optimize and capitalize on functionality in Electron.js?

After creating three custom buttons for the close, maximize, and minimize functions in Electron.js, I encountered an issue. While the close button is functioning properly, I am struggling with implementing the maximize and minimize buttons. In fact, I have ...

Issues arise when attempting to alter the background image using jQuery without browserSync being activated

I am facing an issue with my slider that uses background-images and BrowserSync. The slider works fine when BrowserSync is running, but without it, the animations work properly but the .slide background image does not appear at all. Can someone help me ide ...

Several treeviews for selecting data

I need some help with a specific assignment. The back end code is all set, but I'm struggling with the UI component. The task requires two tree views, one on the left and one on the right. The left tree view will contain states with multiple children, ...

Modal obstructing BsDatePicker

<!-- The Server Modal --> <div class="modal" id="serverModal"> <div class="modal-dialog" style="max-width: 80%;overflow-y: initial !important;" > <div class=" ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

What is the best way to delete a CSS class from a specific element in a list using React?

I need to implement a functionality in React that removes a specific CSS class from an item when clicking on that item's button, triggering the appearance of a menu. Here is my code snippet. import "./Homepage.css" import React, { useState, ...

watchify with gulp requires two saves to update modifications

For a while now, I've been experimenting with watchify and encountering a saving issue. It appears that every time I make a change, I have to save twice for the modifications to reflect in the output. If I add new code to any JavaScript file, the ch ...

utilizing the JavaScript SDK to send alerts to a user's friends on Facebook

I am attempting to send a notification to a user's friend using the JS SDK on a Facebook canvas app, but I'm encountering this error in the console: POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140 c.exten ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...

Creating a unique, random output while maintaining a log of previous results

While working on a recent project, I found myself in need of a custom Javascript function that could generate random numbers within a specified range without any repetitions until all possibilities were exhausted. Since such a function didn't already ...

Leveraging jQuery within a method defined in an object using MyObject.prototype.method and the 'this' keyword

Recently, I've started exploring Object-oriented programming in JavaScript and have encountered a challenge. I'm trying to define an object like the example below, where I am using jQuery inside one of the methods. I'm curious about the best ...

Invalidating the memory in iOS 7.1.1 when using canvas drawImage

When I use the following code on an animation frame, I notice a significant memory leak that eventually causes IOS Safari or Chrome to crash: ctx.drawImage(anotherCanvas, clipX, clipY, clipW, clipH, x, y, w, h); Interestingly, if I don't apply a ...

Click on the form to initiate when the action is set to "javascript:void(0)"

I am working on an HTML step form that needs to be submitted after passing validation and ensuring all fields are filled. The form currently has an action controller called register.php, but also includes action="javascript:void(0);" in the HTML form. What ...

The JSON response is not being returned by the static React App hosted on Microsoft

Seeking assistance from anyone who may have faced and resolved a similar issue. Our React application is deployed on Azure Static Web App and operates smoothly, but we are stuck on configuring it to return JSON instead of HTML in its responses. Within our ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Trouble with implementing Ajax in Express and jquery

My app has a browse page where users can add items as owned or wanted. Currently, when adding an item it redirects back to the general /browse page. However, I want the page to not refresh at all. I'm attempting to achieve this with ajax, but as a beg ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

No specification has been provided for the delivery

I'm currently working with the Meteor framework and I am attempting to send an uploaded file (HTML input) from the client to the server using the npm package Delivery. Below is my code: Client side : var socket = io.connect('http://0.0.0.0 ...