Exercise Knockout Js

Exercise 1

Create two field input your first name and last name. Show full name = first name + last name. Create button have function converts your name to uppercase.

<!--
/**
 * Copyright © 2009-2017 TQ Group. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Knockout JS</title>
        <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
    </head>
    <body>
        <div>   
            <p>First name: <input data-bind='value: firstName' /></p> 
            <p>Last name: <input data-bind='value: lastName' /></p> 
            <h2>Welcome, <span data-bind='text: fullName'> </span>!</h2>  
        </div>
        <button data-bind="click: upper">Click Me</button>
        <script type="text/javascript">
            var ViewModel = function(first, last) {
                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);
                this.isUpperCase = ko.observable(false);
                this.fullName = ko.computed(function() {
                    if(this.isUpperCase())
                        return this.firstName().toUpperCase()  + " " + this.lastName().toUpperCase() ;
                    return this.firstName() + " " + this.lastName();
                }, this);

                this.upper = (function() {
                    this.isUpperCase(!this.isUpperCase());
                });
            };

            ko.applyBindings(new ViewModel("Thong", "Quach"));
        </script>
    </body>
<html>

Exercise 2

Show the text and change color and font size when you mouseover the text and back to original when you mouseout.

<!--
/**
 * Copyright © 2009-2017 TQ Group. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Knockout JS</title>
        <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
        <style>
            .normal {
                color:black;
                font-size:20px;
            }
            .hover {
                color:red;
                font-size:40px;
            }
        </style>
    </head>
    <body>
        
        <div class="normal" data-bind="css: !testEnabled() ? 'normal' : 'hover', event: { mouseover: enableDetails, mouseout: disableDetails }">
           Kiss me now!
        </div>
        <script type="text/javascript">
            var viewModel = {
                testEnabled: ko.observable(false),
                enableDetails: function() {
                    this.css
                    this.testEnabled(true);
                },
                disableDetails: function() {
                    this.testEnabled(false);
                }
            };
            ko.applyBindings(viewModel);
        </script>
    </body>
<html>

Exercise 3

Add value to list and show them. We create a field input, button add have action add value in array,button for action remove items and button for sort the list. Add button only active when input have value, remove button only active when have item selected and sort button only active when list have more than one item.

<!--
/**
 * Copyright © 2009-2017 TQ Group. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Knockout JS</title>
        <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
    </head>
    <body>
        <form data-bind="submit:addlanguage">
            Add Language: <input type="text" data-bind='value:languageToAdd, valueUpdate: "afterkeydown"' />
            <button type="submit" data-bind="enable: languageToAdd().length > 0">Add</button>
        </form>
        <p>Your Languages:</p>
        <select multiple="multiple" height="5" data-bind="options:allLanguages, selectedOptions:selectedLanguages"></select>
        <div>
            <button data-bind="click: removeSelected, enable: selectedLanguages().length > 0 || allLanguages().length > 1">Remove</button>
            <button data-bind="click: sortLanguages, enable: allLanguages().length > 2">Sort</button>
        </div>
        <script type="text/javascript">
            var TestListModel = function () {
                this.languageToAdd = ko.observable("");
                this.allLanguages = ko.observableArray(["Php", "Java", "Javascript", "Python"]);
                this.selectedLanguages = ko.observableArray(["Php"]);
                this.addlanguage = function () {
                    if ((this.languageToAdd() != "") && (this.allLanguages.indexOf(this.languageToAdd()) < 0)) {
                        this.allLanguages.push(this.languageToAdd());
                        this.languageToAdd("");
                    }
                };
                this.removeSelected = function () {
                    this.allLanguages.removeAll(this.selectedLanguages());
                    this.selectedLanguages([]);
                };
                this.sortLanguages = function() {
                    this.allLanguages.sort();
                };
            };
            ko.applyBindings(new TestListModel());
        </script>
    </body>
<html>

Exercise 4

Create a form register include: firstname, lastname, username, password, confirm password, sex, country, hobbies and validate them. Validate: firstname, lastname, username, sex (male & female with radio button), country (dropbox with some country), hobbies(multichoice with checkbox); password at least 6 character and confirm password same password.

<!--
/**
 * Copyright © 2009-2017 Vaimo Group. All rights reserved.
 * See LICENSE.txt for license details.
 */
-->
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Knockout JS</title>
        <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
        <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout-validation/1.0.2/knockout.validation.min.js"></script>
    </head>
    <body>
        <script id="customMessageTemplate" type="text/html">
            <em class="customMessage" data-bind='validationMessage: field'></em>
        </script>
        <fieldset>
            <label>First name: <input data-bind='value: firstName'/></label>
            <label>Last name: <input data-bind='value: lastName'/></label>
            <div>
                <label>User name: <input data-bind='value: username'/></label>
            </div>
            <div>
                <label>Password: <input type="password" data-bind='value: password'/></label>
                <label>Confirm Password: <input type="password" data-bind='value: confirm'/></label>
            </div>
            <div>   
                <label>
                    Country: 
                    <select data-bind='value: country, options: countries, optionsCaption: "Choose one..."'></select>
                </label>
            </div>   
            <div data-bind="foreach: genders">
                <label>
                    <input name="genders" type="radio" data-bind="radioCheck: selected" />
                    <span data-bind="text:name"></span>
                </label>
            </div>
            <div data-bind="foreach: hobbies">
                <label>
                    <input name="hobbies" type="checkbox" data-bind="radioCheck: selected" />
                    <span data-bind="text:name"></span>
                </label>
            </div>    
        </fieldset>
        <button type="button" data-bind='click: submit'>Submit</button>
        <script type="text/javascript">
            ko.validation.rules.pattern.message = 'Invalid.';
            ko.validation.rules['confirmPasswordMatches'] = {
                validator: function (val, params) {
                    var otherValue = params;
                    return val === ko.validation.utils.getValue(otherValue);
                },
                message: 'Passwords do not match.',
            };
            ko.validation.registerExtenders();
            ko.validation.configure({
                registerExtenders: true,
                messagesOnModified: true,
                insertMessages: true,
                parseInputAttributes: true,
                messageTemplate: null
            });
            var mustEqual = function (val, other) {
                return val == other();
            };
            function AppViewModel() {
                var self = this;
                this.firstName = ko.observable().extend({required: true });
                this.lastName = ko.observable().extend({required: true });
                this.username = ko.observable().extend({required: true });
                this.password = ko.observable().extend({required: true, minLength: 6});
                this.confirm = ko.observable().extend({ 
                    required: true, minLength: 6,
                    validation: { validator: mustEqual, message: 'Passwords do not match.', params: this.password }
                }),
                this.genders = [
                    {
                    "name": "male",
                    "selected": ko.observable(true)},
                {
                    "name": "female",
                    "selected": ko.observable(false)}
               
                ],
                this.hobbies = [
                    {
                    "name": "sport",
                    "selected": ko.observable(true)},
                    {
                        "name": "music",
                        "selected": ko.observable(false)},
                    {
                        "name": "traveling",
                        "selected": ko.observable(false)}
               
                ],             
                this.countries = ['VN', 'JP', 'USA', 'Eng'];
                this.country = ko.observable().extend({ required: true });                
                this.submit = function () {                   
                    if (this.errors().length == 0) {
                        alert('Success.');
                    } else {
                        alert('Please check your submission.');
                        this.errors.showAllMessages();
                        alert(viewModel.errors());
                    }
                }
            }
            var viewModel = new AppViewModel();
            ko.bindingHandlers.radioCheck = {
                init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
                    element.checked = valueAccessor()();       
                }
            };
            viewModel.errors = ko.validation.group(viewModel);
            ko.applyBindings(viewModel);
            ko.validation.registerExtenders();
            ko.applyBindings(new UserAccount({}));
        </script>
    </body>
<html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s