简体   繁体   中英

Toggle state of button based on select dropdown using knockout.js

I've got a small form I'm trying to add logic to, and right now I'm stuck trying to change the state of an 'add' button between enabled and disabled based on the selected value of a dropdown menu.

My DOM markup is the following:

<div>
    <select data-bind="options: myOptions, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption: 'Select...'"></select>
    <input type="text" class="optional" />
    <input class="addButton" type="submit" name="addButton" value="ADD" data-bind="enable: addButtonState" />
</div>

And my current Knockout.js code is the following:

self.addButtonState = ko.observable(false);
self.toggleAddButtonState = function () {
  // Some logic to go here
}

As you can see, the default value for the dropdown menu is select... . When this default is presented, I want the addButton to be in the disabled state. However, when any other option is selected, it can be enabled. The optional text field should not matter.

How can I accomplish this?

well this can be done in alternate way with no extra logic

Working Fiddle Here

view Model :

self.selectedVal=ko.observable();
self.toggleAddButtonState = function () {
  // do what ever you want 
}

View :

<div>
    <select data-bind="options: myOptions, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption: 'Select...',value: selectedVal"></select>
    <input type="text" class="optional" />
    <input class="addButton" type="submit" name="addButton" value="ADD" data-bind="enable: selectedVal" />
</div>

The trick here is simple. Initially selectedVal is undefined and you can use this and make binding to your enable .

Extra coding can be avoided here ie for change in dropdown we need to write computed or subscribe etc

You can use a computed observable: http://knockoutjs.com/documentation/computedObservables.html

//this is for the selected user
self.user = ko.observable();

self.addButtonState = ko.computed(function() {
    return self.user() != undefined;
});

You need to also add the value binding to the select to bind the selected value to the newly added user observable:

<select data-bind="options: myOptions, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption: 'Select...', value: user"></select>

http://jsfiddle.net/74dh736s/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM