I am experiencing an issue where my observable value gets reset after setting it in KnockoutJS + Chosen

Currently, I am in the process of creating a user interface for building charts. Users have the ability to select fields from a database in order to construct a graph. Additionally, these graphs come with a refresh interval dropdown feature.

Everything functions as expected until I attempt to retrieve a value from a saved "view". Upon setting the value, it appears to be successful when I subscribe to the RefreshInterval variable.

However, the value is instantly reset to the 0 index within my options array.

https://i.sstatic.net/3yQjR.png

[html]

<div class="wrapper wrapper-content" id="charts">
  <select id="interval" data-bind="options: RefreshIntervals,
    optionsText: 'Value',
    value: RefreshInterval,
    chosen: {
      disable_search_threshold: 0,
      width:'175px',
      no_results_text: 'No results!',
      placeholder_text_single: 'Select an interval',
      search_contains: true,
    }">
  </select>
</div>

[javascript]

function ViewModel() {
    var self = this;
    this.RefreshIntervals = ko.observableArray([
                new Interval(0, "Never"), new Interval(10, "seconds"), new Interval(1, "minutes"), new Interval(5, "minutes")
            ]);
    this.RefreshInterval = ko.observable(new Interval(5, "minutes"));
};

var Interval = (function () {
    function Interval(length, measurement) {
    var _this = this;
    this.Length = 0;
    this.Measurement = "";
    this.Value = "";
    this.TimeoutValue = 0;
    this.GetTimeoutValue = function () {
      switch (_this.Measurement) {
        case "seconds":
          return _this.Length * 1000;
        case "minutes":
          return _this.Length * 60000;
        default:
          return 0;
      }
    };
    this.Length = length;
    this.Measurement = measurement;
    if (length == 0 || measurement == "Never") {
      this.Value = "Never";
    }
    else {
      this.Value = this.Length + " " + this.Measurement;
    }
    this.TimeoutValue = this.GetTimeoutValue();
  }
  return Interval;
}());

ko.bindingHandlers.chosen =
{
    init: function (element, valueAccessor, allBindings) {
      $(element).chosen(valueAccessor());

      // trigger chosen:updated event when the bound value or options changes

      $.each('value|selectedOptions|options'.split("|"), function (i, e) {
          var bv = allBindings.get(e);
          if (ko.isObservable(bv)) {
            bv.subscribe(function () {
              $(element).trigger('chosen:updated');
            });
          }
      });
    }
};
var vm = new ViewModel();
ko.applyBindings(vm, document.getElementById("charts"));

I have provided a fiddle link for reference: Fiddle

I have three dropdown boxes that require data population. My goal is for the value to represent the actual element rather than a separate value field, which would then need to be correlated back to the object within the options list due to potential changes in the options list.

If you have any suggestions on how I can address this issue, please let me know.

Answer №1

The <select> element's value attribute was not being generated correctly. To fix this issue, you must include optionsValue: 'Value' in your binding code.

In Knockout, there is a limitation where you cannot directly bind the selected value to the enclosing object.

As a workaround, you can programmatically set the desired option like this:

vm.RefreshInterval("10 seconds");

The computed will then return the string value instead of the entire object. To retrieve the object, you can do the following (or use underscore or lodash for a more elegant solution):

this.RefreshInterval.subscribe(function(newValue){
 var obj = null;
 for(var i=0; i<self.RefreshIntervals().length; i++) {
   var interval = self.RefreshIntervals()[i];
   if(interval.Value === newValue) {
     obj = interval;
     break;
   }
 }
 console.log(obj);
); 

Also, remember to add optionsValue: 'Value',

For an updated working example, check out this JsFiddle link

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

Is it preferable to load JQuery before displaying the content of the HTML page?

My mobile site is set to 762px width, which is ideal for a PC screen. However, I am trying to style it to be 320px wide for an iPhone using JQuery. The issue I am facing is that when the page loads, it initially appears at the larger width and then resizes ...

Tips for safeguarding AJAX or javascript-based web applications

Utilizing AJAX, this function retrieves information about an image in the database with the ID of 219 when a button is clicked. Any visitor to this webpage has the ability to alter the JavaScript code by inspecting the source code. By modifying the code a ...

Steps for creating a PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...

What could be the reason for v-model not functioning properly within vue.extend?

I've configured a page structure similar to the following: <main id="app"> <div id="mount-place"></div> </main> <script type="text/x-template" id="my-template"> ...some code her ...

Generating and saving a PDF file using a binary string in JavaScript or TypeScript

A server response to an Axios request contains the content of a PDF as a binary string. export const fetchPDFfile = async (id: string): Promise<string> => { const { data } = await http.get<string>(`${baseUrl}/${id}.pdf`); return data; } ...

error message remains visible even after correct input is entered

I am new to React and attempting to create a multi-step form using Reactjs and Material-ui. The form validation and submit buttons are working perfectly fine. However, I have encountered an issue with the code where if a field is empty and I try to proceed ...

Display several modal pop ups using AngularJS

I'm currently using AngularJS and I have a requirement where I need to check if a student ID exists in the database when a user clicks a button. If the student ID is found in the database, I want to display #modal1, otherwise show #modal2. Is it achie ...

What is the best way to store a jQuery AJAX response in a PHP variable?

How can I pass a jQuery ajax response into a PHP variable after success in my code: process.php $start = ""; $end = ""; if(isset($_POST['tampStart'])) { $start = $_POST['tampStart']; } if(isset($_POST[& ...

Adding custom CSS and JavaScript to the TYPO3 backend: A step-by-step guide

Is there a way to incorporate css and javascript files into the backend? I'm aiming to enhance custom created content elements with these files, making them more visually appealing for users. Platform: TYPO3 v9 Method: Composer Mode Purpose: Cu ...

Exploring VueJs 3's Composition API with Jest: Testing the emission of input component events

I need help testing the event emitting functionality of a VueJs 3 input component. Below is my current code: TextInput <template> <input v-model="input" /> </template> <script> import { watch } from '@vue/composition-api&ap ...

What is the process for modifying the user agent?

I'm struggling with phantom, the node.js wrapper for phantomjs. This is the approach needed in native phantomjs. page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/5 ...

Deciphering arrays from javascript with PHP

I'm struggling to understand how to transfer a JS array into PHP. The data I have to work with is structured like this: var arrLow = [ { "e": "495864", "rank": "8678591", "rankmove": "<p><img src='up.php?uStyle=144'> UP 495864" ...

Explore the possibilities with Intel XDK's customizable keyboard feature

I recently started using Intel XDK for development and I encountered the following issue: I have an input text field (HTML) and I need to restrict user input to only numbers, decimals, and negative sign when they click on the field. How can I achieve this ...

Issue with HTML5 Video Play on Hover Functionality Ceases to Work Upon Loading Dynamic Content

I recently implemented a feature on my WordPress site that allows videos to start playing when the mouse hovers over their thumbnails and pause when it leaves. However, I encountered an issue where this function works perfectly upon initial page load but f ...

How can AJAX be used to execute a PHP script that deletes a record from a database table?

Yesterday, I asked for help on how to save user-generated blog posts and I successfully tackled the database aspect of it. Now, my next goal is to be able to delete a blog post upon clicking a button with an onclick event. After researching extensively onl ...

Sharing a Redux action with nested child components

The current structure I am working with looks like this: UserPage -> Container |-----UserList -> Dumb Component |--- User ->Dumb Component My action and dispatch are connected to the container, which is UserPage. function mapStateToProps(state) ...

Using Laravel to submit a form with identical input names via AJAX

Seeking assistance with my ajax function. A form I have is submitting data with the same input name. Without using JavaScript, I can insert multiple input data with the same name easily, Here is the structure of the submitted data {"_token":& ...

When the initial image URL returns a 404 error, the ng-src path does not automatically switch to the alternative

I'm currently working on a webpage where I want to show an image only if the URL of that image is valid, using AngularJS. The challenge I'm facing is that ngIf only checks whether a value is null or not. So, even if the URL returns a 404 error, ...

Using jQuery to fetch and display content only when the user hovers over

Looking to optimize page loading speed by minimizing the loading time of social icons such as Facebook Like and Twitter follow buttons. Considering displaying a static image of the like buttons initially, with the actual buttons appearing on mouse hover. ...

Having Trouble Implementing Canvas in My Vue.js Project

I needed to take a screenshot in my vue.js project, so I decided to use html2canvas. Here are the steps I followed to implement html2canvas: Step 1-: Install 'html2canvas' into my project npm install html2canvas Step 2-: Import html2canvas int ...