Search code examples
knockout.jsknockout-validation

Login with several options, show/hide other fields


My page will contain 2 login alternatives.

Alt. 1 : Fields for database name, username and password. Alt 2: Field for the database connectionstring.

When you start typing in a field in alternative 1, i want the connectionstring field to hide and opposite... if you start typing in the connectionstring field i want the other 3 fields to hide.

Is there a easy way to accomplish this with knockout validation ?

Thanks on forehand!


Solution

  • Assuming your values are part of your view model, you can use the visible attribute in data-bind to check the length of the values:

    Sample Fiddle: http://jsfiddle.net/RkaB3/1/

    View Model:

    var ViewModel = function () {
        var self = this;
        self.alt1 = ko.observable('');
        self.alt2 = ko.observable('');
    };
    
    ko.applyBindings(new ViewModel());
    

    Markup:

    <div data-bind="visible: alt2().length == 0">
        <p>Alt1 Login</p>
        <input data-bind="value: alt1"></input>
    </div>
    <div data-bind="visible: alt1().length == 0">
        <p>Alt2 Login</p>
        <input data-bind="value: alt2"></input>
    </div>    
    

    You may want to do something a bit more intelligent on the Alt1 option that contains 3 fields. For example, use a ko.computed function that checks all 3 fields and return true if any of them contain a value:

    Updated Fiddle with computed

    self.usingLoginAlternative1 = ko.computed(function () {
        return !self.connectionString();
    });
    
    self.usingLoginAlternative2 = ko.computed(function () {
        return !(self.server() || self.database() || self.userId() || self.password());
    });
    

    http://jsfiddle.net/RkaB3/4/