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

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Struggling to display a navigation menu on angular 1 with complex nested json structure

I have set up a navigation bar using JSON data fetched by an Angular service. Everything is working fine with my service and controller, but I am facing difficulty in displaying the nested JSON data in my view. Here is the JSON data: { "menu": [ ...

Tips for incorporating jQuery UI into Angular 6

No matter how many methods I have tried from StackOverflow, I cannot seem to get jquery-ui to work in my angular 6 component. Here's what I've attempted: I went ahead and ran npm install jquery jquery-ui to install both jquery and jquery-ui. ...

What causes Three.js OBJ conversion to render as mesh successfully but log as undefined?

I'm just getting started with Three.js and I'm experimenting a lot. Although I'm new to Javascript as well, the issue I'm facing seems to be more about variable scoping and callback function protocols than it is about Three.js itself... ...

I want to use React Bootstrap and Next.js to retrieve the text from a textbox in a React Component and then send it back to my Index.js file. How can I accomplish this task?

I need some assistance. Currently, I am facing a challenge. I am trying to retrieve data from one of my React Components named ParameterList. This component contains a React-Bootstrap Form.Control element for numerical input. My goal is to take the value ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Replace the ngOnDestroy method

Is there a way to complete an observable when the ngOnDestroy is triggered? I'd prefer not to create new child components when dealing with just one component instance. I attempted to override ngOnDestroy by modifying the function in the component&apo ...

Exploring the capability of the Videoshow NPM module in conjunction with

I've been working on using videoshow to convert a series of images into a video. I've made several changes to my code, but it seems like it's pretty much the same as what's described in the module's documentation. However, I keep e ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

Steps for deactivating a button until the form has been submitted

Click here for the Fiddle and code sample: $(".addtowatchlistform").submit(function(e) { var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Additional line $.post(url, data, function(data) { try { ...

Hover over the first element to remove its class and replace it with a different element

I am attempting to develop a function that adds the class = "actived" to the first Element. This class has a CSS style that highlights the element in question. I have a list of 4 lines and I want the first one to automatically receive this class, while t ...

What is the best way to isolate a single element within a for loop and exclude all others?

I have implemented a dynamic Ajax call to compare the string entered in the text field (representing a city name) with the "type" value in a JSON array. As I iterate through the elements of the array, I am checking the values associated with the key "type ...

Formik integration issue with MUI DatePicker causing error message: "date.isBefore is not a function"

I'm currently creating a form in React using Formik and MUI components. However, I encountered an error that says: date.isBefore is not a function TypeError: date.isBefore is not a function at DayjsUtils.isBeforeDay (http://localhost:3000/static/j ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

Event handlers in JQuery are not connected through breadcrumb links

Wondering how to ensure that the click handler is always attached in my Rails 4.1 app where I am using JQuery-ujs to update cells in a table within the comments#index view. In my comments.js.coffee file, I have the following code snippet: jQuery -> ...

What is the best way to delete a jQuery.bind event handler that has been created for an event

I have a div and I need to assign two scroll functions to it, but I also want to remove one of them after a certain condition is met. <div id="div1" class="mydivs"> something </div> <div id="div2">Some crap here</div> <script&g ...

What sets apart the CSS file directories in a React application compared to those in an Express server?

For instance, there is a public folder that contains all the css files, and a separate view folder for ejs files. When linking the css file in the ejs file, the code usually looks like this: <link rel=”stylesheet” href=”styles.css”> or like ...

Encountering timeout issues with Next.JS fetch and Axios requests on Vercel production environment

I've been encountering an issue where I am unable to fetch a specific JSON data as it times out and fails to receive a response on Vercel deploy. The JSON data I'm trying to fetch is only 18KB in size and the fetch request works perfectly fine in ...

Generate new variables based on the data received from an ajax call

Suppose there is a .txt file containing some integers separated by spaces, like '22 1 3 49'. I would like to use Ajax to read the file as an array or list, and then save each integer as a JavaScript variable. Currently, this code reads all cont ...