Can the optionsText be shown while saving the optionsValue in a dropdown menu?

Here is the code snippet I am currently working with:

var model = function() {
    this.nameSomething = ko.observable('');
    this.nameId = ko.observable(0);
};

var vm = (function() {
var myList = [{ id: 1, type: 'foo1'}, { id: 2, type: 'foo2' }, { id: 3, type: 'foo3' }],
    selectedModel = ko.observable(model);
    
    return {
        myList: myList,
        selectedModel: selectedModel
    };
}());

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="with: selectedModel">
    <select data-bind="options: $root.myList,
                       optionsText: 'type',
                       optionsValue: 'type',
                       value: nameSomething"></select><br />
    Display this: <span data-bind="text: nameSomething"><br />
    Store this: <span data-bind="text: nameId"><br /> <!-- not displaying anything -->
    <pre data-bind="text: ko.toJSON($root.selectedModel, null, 2)"></pre>
</div>
    

Can I save the value of optionsValue in nameId and the text from optionsText in nameSomething when the option is loaded/changed?

I need to show the selected text in the UI while storing the corresponding value in the database.

Any assistance on this issue would be greatly appreciated. I am also open to any tips for beginners using Knockout JS.

UPDATE

Added a working example

Answer №1

One way to solve this is by utilizing the entire object as the "selected value". This approach allows for a clear separation between what is displayed and what is stored.

var defaultItem =  {
    id: 1,
    type: 'foo1',
};

var vm = (function() {
var myList = [{ id: 1, type: 'foo1'}, { id: 2, type: 'foo2' }, { id: 3, type: 'foo3' }],
    selectedModel = ko.observable(defaultItem);
    
    return {
        myList: myList,
        selectedModel: selectedModel
    };
}());

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
    <select data-bind="options: myList,
                       optionsText: 'type',
                       value: selectedModel"></select><br />
    <div data-bind="with: selectedModel">
        <span>Display this: </span><span data-bind="text: type"></span><br />
        <span>Store this: </span><span data-bind="text: id"></span><br />
        <pre data-bind="text: ko.toJSON($root.selectedModel, null, 2)"></pre>
    </div>
</div>
    

Answer №2

If you choose not to identify the optionsValue, the selected value will be set to the full object and you can customize it as you wish... You will have access to all properties (if I understood your question correctly).

<div data-bind="with: selectedModel">
    <select data-bind="options: $root.myList,
                       optionsText: 'type',
                       value: nameSomething"></select><br />
        Display this: <span data-bind="text: nameSomething().id"><br />
    Store this: <span data-bind="text: nameSomething().nameId"><br /> <!-- not displaying anything -->
    <pre data-bind="text: ko.toJSON($root.selectedModel, null, 2)"></pre>
</div>

Take a look at my fiddle here http://jsfiddle.net/bgap47d4/2/

Answer №3

It is not achievable directly. There are a few methods you can consider:

  1. Utilizing a computed function (such as pureComputed) to retrieve the value by key from the array
  2. Creating an observable and subscribing a function to the nameId that updates the observable

You have the option to use the selectedOptions binding and either subscribe to or fetch the currently selected option's value from the bound observableArray, but this serves as an alternative.

This solution provides guidance for your issue, demonstrating the structure that should be implemented in your viewmodel using the first method.

var viewModel = (function() {
  
  var list = ko.observableArray(
    [{ id: 1, type: 'foo1'}, 
     { id: 2, type: 'foo2' }, 
     { id: 3, type: 'foo3' }]
  );
  
  var selectedId = ko.observable();
  
  var selectedType = ko.pureComputed(function() {
    return list().find(function(item) { return item.id === selectedId(); }).type;
  });
  
  return {
    list: list,
    selectedId: selectedId,
    selectedType: selectedType
  };
  
})();

ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
    <select data-bind="options: list,
                       optionsText: 'type',
                       optionsValue: 'id',
                       value: selectedId"></select><br />
    Display this: <span data-bind="text: selectedType"></span><br />
    Store this: <span data-bind="text: selectedId"></span><br /> <!-- not displaying anything -->
    <pre data-bind="text: ko.toJSON($root.selectedModel, null, 2)"></pre>
</div>

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

Working with Angular: Accessing SCSS variables from style.scss using JavaScript inside a component

I am working on an Angular 9 application that utilizes Angular Material and has two themes, namely dark and light. These themes are defined in the style.scss file as follows: $rasd-dark-text-color: mat-palette($mat-grey, 300); $rasd-light-text-color: mat-p ...

Using jQuery UI to dynamically add a widget based on a specific class, rather than relying on

Exploring the world of Apache Cordova and jQueryUI is a new adventure for me. I am currently experimenting with formatting the layout of my index.html using jQueryUI. As mentioned in this section of the jQueryUI tutorial, a widget can be added using the f ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Using Angular 2 to pass a function as an argument to a constructor

How can I create a custom @Component factory where a function is called to return a component, passing the widgetName to the constructor or super constructor? export function createCustomKendoComponent(selector: string, **widgetName**: string) { @Co ...

Data within React/Next.js will remain unchanged even after a link has been clicked

When using Next.js and clicking on a Link, the new page URL will open as "/component/product". However, the product data is not updated in the Redux store. The page needs to be refreshed in order to update the state data. import Link from "n ...

How to send an html form with php, store it in a MySQL Database, and utilize Ajax and jQuery for

As a beginner in PHP form creation, I have been exploring various tutorials and combining different techniques to create my form. However, I am facing challenges as none of the tutorials cover everything comprehensively from beginning to end. While I beli ...

Exploring the power of jQuery closures and handling events like mouseover and mouseout

I'm currently grappling with the concept of utilizing closures in conjunction with jQuery event functions. The challenge I am facing involves creating rounded shapes on the screen that stop and fade when hovered over, then resume fading when the mous ...

What is the reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Sending a single data point via Ajax on the client side

I am facing an issue with connecting frontend and backend systems. I want to send a single value (radio1Value) from a JavaScript function using jQuery AJAX upon clicking. Is the function structured correctly as I have written it? If yes, how should the R ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Adding the tasksMap to the dependency array in the React useEffect hook will result in an endless loop

I'm facing an issue with adding tasksMap to the useEffect dependency array, as it causes an infinite loop. Can someone guide me on how to resolve this? To ensure that the user sees an updated view of tasks that are added or modified, I need the app to ...

What is the method used by react-create-app/react-scripts to locate the entry point file?

I'm confused about how npm start locates the src/index/js file to begin the rendering process in this helpful tutorial. I've searched everywhere but can't seem to find any information on the configuration. Can anyone provide some insight? ...

Extracting address from a string containing HTML line breaks and apostrophes using JavaScript

I need help with parsing an address that is in a string format like the following: "1234 Something Street<br>Chicago, IL 34571<br>" I am struggling to extract and assign it to separate variables: var street = ...; var city = ...; var state = ...

Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { } } When the user performs a search, I populate the filter i ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...

Can anyone tell me where to find the unminified version of Bootstrap 3's docs.min.js file?

Could someone please provide me with the original version of this file? I've been trying to search for it in the project but haven't had any luck. You can find it here: https://github.com/twbs/bootstrap/blob/master/docs/assets/js/docs.min.js. ...

"Error encountered when attempting to call the requestFocus() method on a Java applet from JavaScript

I'm encountering an issue with calling the requestFocus() method in JavaScript. Uncaught TypeError: Object #<HTMLAppletElement> has no method 'requestFocus' Below is my JavaScript code within the <head> tags: function onLoad() ...

Setting the font size for the entire body of a webpage globally is ineffective

Technology Stack: Nuxt.js + Vuetify.js Problem: Unable to set global body font size Solution Attempt: I tried to adjust the body font size to 40px in ~/assets/style/app.styl: // Import Vuetify styling ...

Unit tests manipulating JavaScript functions to return undefined values

Currently, I am in the process of testing some JavaScript functions within a larger React application. These functions heavily utilize the module pattern, which leads me to believe that my misunderstanding lies within this pattern. The script I am testing ...

Using React.js - Discover the best way to incorporate a function within a child component to unmount a different child component from the same parent, and then mount a new component in its place

Consider this scenario: import React, { Component } from 'react'; import BodyContent from './BodyContent'; import BottomOne from './BottomOne'; import BottomTwo from './BottomTwo'; class App extends Component { re ...