How to use Knockout JS Array Map to make select option binding default to default value based on input condition?


asynchronous

I use Computed Observableand bind data to select options Array Map.

Using the following code structure, how can I set the "Country" as the default value in the select option? For example: if the user is from, Albaniaset the default country to Albania. Note that I am using and need to use the selected value as an argument to another function.

Complete code:

(function(){

    var self = this;

    self.SelectedCountry = ko.observableArray([]);
    self.CountryData = ko.observableArray([]);

    $.getJSON('https://restcountries.eu/rest/v1/all', function(data){

        self.CountryData(data);

    });

    function viewModel(){

      // Add some possible logic to make country default based on input
      // from user. E.g. If data.alpha3Code === '1234'

        self.Countries = ko.computed(function () {
            return ko.utils.arrayMap(CountryData(),

                    function (data) {

                        return {

                            Name: data.name + ' ' + data.capital,
                            value: data.alpha3Code
                        }

                    });

        }).extend({notify: 'always'})
    }

    self.Location = ko.computed(function () {
        if (self.SelectedCountry()) {
            return ko.utils.arrayFilter(CountryData(), function (item) {
                return item.alpha3Code === self.SelectedCountry().value;
            });
        }
    });

    ko.applyBindings(new viewModel());

})();

Working example on JSFiddle :

Roy

Your code has many problems here.

  1. SelectedCountryshould be an observable, not an observableArray
  2. viewModel is not the correct constructor and should not be used new(I got rid of it completely)
  3. you should pass selftoapplyBindings
  4. You may want to optionsValue: 'value'choose binding
  5. selfShould be initialized to an empty object. thisis the global object where you complete the action. You probably meant to wrap it all in the constructor.
  6. You need to be selfat the top of the CountryDatacalculation .
  7. position should only return names, not arrays, because if SelectedCountryundefined, there is no array and [0]will break

Forget all of that, you just need to set the value SelectedCountryand the selection will update accordingly. The only trick is that you need valueAllowUnset: trueto add another binding to the select to tell it that the value you select may not exist (at least not until the data is loaded).

(function() {

  var self = {};

  self.SelectedCountry = ko.observable('BHR');
  self.CountryData = ko.observableArray([]);

  $.getJSON('https://restcountries.eu/rest/v1/all', function(data) {

    self.CountryData(data);

  });

  self.Countries = ko.computed(function() {
    return ko.utils.arrayMap(self.CountryData(),

      function(data) {

        return {

          Name: data.name + ' ' + data.capital,
          value: data.alpha3Code
        }

      });

  }).extend({
    notify: 'always'
  })

  self.Location = ko.computed(function() {
    if (self.SelectedCountry()) {
      var match = ko.utils.arrayFilter(self.CountryData(), function(item) {
        return item.alpha3Code === self.SelectedCountry();
      })[0];
      if (match) {
        return match.name;
      }
    }
  });

  ko.applyBindings(self);

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: Countries, optionsText: 'Name', optionsValue: 'value', valueAllowUnset: true, value: SelectedCountry"></select>

<p>Welcome! You are from:</p> <span data-bind="text: Location()"></span>

Related


Default selection option based on input value

Kurai Bankusu I have the following selecton my form <select id="select-1"> <option value="11">Option 11</option> <option value="12">Option 12</option> <option value="13">Option 13</option> </select> and hidden input <input id="hidden-input-1" valu

Default selection option based on input value

Kurai Bankusu I have the following selecton my form <select id="select-1"> <option value="11">Option 11</option> <option value="12">Option 12</option> <option value="13">Option 13</option> </select> and hidden input <input id="hidden-input-1" valu

How to set default value of select option when mapping array

Amanda Conda I am using CustomInput from reactstrap. I am setting the type to be selected. In my CustomInput type="select" I map the options in an array. I need to set the default value in the select to the specific option being mapped. E.g. I like to default

React.js: How to set default value in select option?

Grevan I'm trying select-optionto implement in React using React custom hooksand am trying to fetch data from a Web API in . I select optionam able to display based on categories (food in my case). But when I choose the default value to display the data, the s

How to make <option> the default value in HTML?

Jerry I would like to select one <option>from the <select>menu as the default, not like use <option selected="selected">. I tried using onloadevents, but the page reloads indefinitely and doesn't allow other options to be selected. HTML code: <html> <body onlo

How to set default value of select option angle

Callan system I want to set default value for select option "John" in ngOninit (on page load). I'm not sure if I'm using the select option correctly. Please correct me if I'm wrong. I try to set values using form groups and form controls. But I can't set the d

How to select option based on input value?

password I have a similar input and a in my page select. If I enter an input value, I want to automatically select the option by its value. The problem is that it works for one input, but I have many such inputs, one same page and a script for all of them chan

How to create wrapper function for default knockout binding

subarachnoid space I'm showing a huge table structure with knockouts. The user can delete a row by clicking the checkbox on the row: data-bind="checked: row.removed" The problem is that the table has to be re-rendered on click, which can take a second or two

How to create wrapper function for default knockout binding

subarachnoid space I'm showing a huge table structure with knockouts. The user can delete a row by clicking the checkbox on the row: data-bind="checked: row.removed" The problem is that the table has to be re-rendered on click, which can take a second or two

How to create wrapper function for default knockout binding

subarachnoid space I'm showing a huge table structure with knockouts. The user can delete a row by clicking the checkbox on the row: data-bind="checked: row.removed" The problem is that the table has to be re-rendered on click, which can take a second or two

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

md - select default value with condition

Dizzy New I'm using md-select to select the year, there is a case where when you first fill out the form you get the default value for the most recent year, otherwise you get the previous value. Here is my view (slim format) md-input-container flex="" label