mishs8
mishs8

Reputation: 73

Knockout js - How to change dropdown value to previous value if certain condition is not matched

knockout js - In my HTML page, I have a dropdown and JQgrid in which user can add new rows. if user changes dropdown value before saving grid data , i want to alert user if he wants to save grid data or continue. if user wants to save data, dropdown value should be old value else new value.

I am facing issue that dropdown value is getting changed to new value.

i have knockout js subscribe method on selectedItem of dropdown. in subscribe method, logic to populate grid is present.

Upvotes: 3

Views: 1087

Answers (1)

Jason Spake
Jason Spake

Reputation: 4304

The subscribe method on an observable tells you what the value has been changed to after it's been changed, so unfortunately it's already too late to cancel. I think you could accomplish what you want by binding to the change event instead of using the value binding, and manually updating the observable with the new value if it passes your conditions.

var viewModel = function() {
  var self = this;
  self.Options = [1, 2, 3, 4];
  self.selectedOption = ko.observable();
  self.selectedOption.subscribe(function(newValue) {
    console.log(newValue);
  });

  self.isOptionValid = function(value) {
    return (value > 2);
  }

  self.onChange = function(viewModel, event) {
    var target = event.target;
    var newValue = $(target).val();
    if (self.isOptionValid(newValue)) {
      self.selectedOption(newValue);
    } else {
      console.log('Invalid selection');
      $(target).val(self.selectedOption()); //reset to previous value
    }
  }
}

ko.applyBindings(new viewModel());
<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>

<div>
  <span>Pick a number greater than 2</span><br/>
  <Select data-bind="options: Options, optionsCaption: '', event: {change: onChange}">  
  </Select>
</div>

This has the disadvantage of only being a one-way binding meaning that if your observable's value changes from some other source then the dropdown will not be updated with that new value. If you need to preserve a two-way binding then you might want to try a custom binding handler instead, something like: gated value binding

Upvotes: 2

Related Questions