Kamran.Khan
Kamran.Khan

Reputation: 13

Knockout JS Disable dropdown option after selecting it and re enabling it after clicking a button X

I want to create a dropdown with three options

var viewModel = {

    items: ko.observableArray(['one', 'two', 'three'])
};

If I click on one, the currently selected item 'one' will be disabled, and will only be enabled in the dropdown if I click on a button. Can someone please help me with code sample and logic. Please the sample code should only by in knockout JS no jquery or javascript please.

Upvotes: 1

Views: 1371

Answers (1)

Mateen Kajabadi
Mateen Kajabadi

Reputation: 3644

That would be better if you had shown what you've attempted.
There are different ways to do it. Here is an approach using knockout:
Example : https://jsfiddle.net/kyr6w2x3/43/

HTML :

<select data-bind="foreach: items, value: selectedOption">
  <option data-bind="value: value, text:name, attr: {'disabled' :IsDisable}" ></option>
</select>
<input type="button" data-bind="click: btnClicked" value ="Click To enable one">

JS Model :

  function YourViewModel() {
    var self = this;
    var options = [ {name: 'One', value: '1'},
                    {name: 'two', value:'2'},
                    {name: 'three', value:'3'}
                   ];
    self.items = ko.observableArray();
    self.selectedOption = ko.observable();

    $.map(options, function (item) {
       self.items.push(new drowpDownOptionViewModel(item));
    });
    // subscribe to selected option 
    self.selectedOption.subscribe(function (newValue) {
        // if One is selected make it disable
        if (newValue === 1){
           ko.utils.arrayForEach(self.items(), function (item) {
              return item.IsDisable(item.value() === 1);
          });
        }
    }, self);

    self.btnClicked = function (){
    ko.utils.arrayForEach(self.items(), function (item) {
         item.IsDisable(false);
     });
    }
  }
 function drowpDownOptionViewModel (data){
    var self = this;
    self.name = ko.observable(data.name);
    self.value = ko.observable(data.value);
    self.IsDisable = ko.observable(false);
 }


ko.applyBindings(new YourViewModel());

Another example based on comment :https://jsfiddle.net/kyr6w2x3/44/

Upvotes: 2

Related Questions