Kamran.Khan Kamran.Khan - 1 year ago 298
Javascript Question

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.

Answer Source

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/


<select data-bind="foreach: items,value:selectedOption">
  <option data-bind="value: value, text:name, attr:{'disabled' :IsDisable}" ></option>
<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) {
 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());

Updated Example :https://jsfiddle.net/kyr6w2x3/44/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download