Ancient
Ancient

Reputation: 3057

show selected item from dropdown as text binding

I simply create a select list binding as following

<select id="listingstatus"   data-bind="options: ListingTypeArrary, optionsText: 'Text', optionsValue: 'Value', selectedOptions: ListingType" ></select>

My Model

var listArray = JSON.parse([{
    "Selected": false,
    "Text": "Commercial",
    "Value": "4"
}, {
    "Selected": false,
    "Text": "Residential",
    "Value": "5"
}]);
self.ListingTypeArrary = ko.observableArray();
$.each(listArray, function (index, value) {

    var obj = {};
    obj["Text"] = value.Text;
    obj["Value"] = value.Value;
    self.ListingTypeArrary.push(obj);

});

self.ListingType = ko.observable('@Model.ListingTypeId'); // @Model.ListingTypeId will be equals to 5

after doing this knockout render my dropdown/selectlist perfectly . But i have a requirement that i don't have to show dropdown i just need to show selected item as text . Any one can help me ?

Thanks in advance .

Upvotes: 0

Views: 3948

Answers (1)

steveluscher
steveluscher

Reputation: 4228

If I understand correctly, once a user has made a selection, you want the <select> to disappear, and a textual label to appear in its place.

You will have to compute that label based on the selected Value, then display either the <select> or a text label, conditionally.

HTML

<!-- ko ifnot: SelectedListingText -->
<select id="listingstatus" data-bind="
    options: ListingTypeArray,
    optionsText: 'Text',
    optionsValue: 'Value',
    value: ListingType"></select>
<!-- /ko -->

<!-- ko if: SelectedListingText -->
<span data-bind="text: SelectedListingText"></span>
<!-- /ko -->

Javascript

Original Data

var listArray = [
  {
    "Selected": false,
    "Text": "Commercial",
    "Value": "4"
  },
  {
    "Selected": false,
    "Text": "Residential",
    "Value": "5"
  }
];

Options for the select

// Synthesize the listing type array for the select
ListingTypeArray = ko.observableArray([{ Text: 'Choose one', Value: null }]);
$.each(listArray, function (index, value) {
    var obj = {};
    obj["Text"] = value.Text;
    obj["Value"] = value.Value;
    ListingTypeArray.push(obj);
});

Storage for the selected option

// The chosen listing type
ListingType = ko.observable();

The computed text label

// Compute the label text based on the selected Value
SelectedListingText = ko.computed(function () {
  type = ListingType();
  if(!type) return;

  // Find the text associated with this type
  var foundListingTypeName;
  $.each(listArray, function (index, listingType) {
    if(listingType.Value == type) {
      foundListingTypeName = listingType.Text;
      return false;
    }
  });

  return foundListingTypeName;
});

In action: http://jsfiddle.net/steveluscher/rmnMt/

Upvotes: 1

Related Questions