Knockoutjs.com - Hello World Example

masking social security number

by shuja uddin

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div class='liveExample'>   
    <p>tax Raw: <input data-bind='value: taxid' /></p> 
   <h2>ssn, <span data-bind='text: ssn'> </span>!</h2>  
</div>

CSS

body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }

JavaScript

// Here's my data model
var ViewModel = function(taxid) {
    this.taxid = ko.observable(taxid);
    
 
    this.ssn = ko.pureComputed({
        read: function () {
            return (this.taxid().replace(/^\d{3}[a-z]*/, "###")) 
        },
        write: function (value) {
            var lastSpacePos = value.lastIndexOf(" ");
            if (lastSpacePos > 0) { // Ignore values with no space character
                this.taxid(value.substring(0, lastSpacePos)); // Update "firstName"
                
            }
        },
        owner: this
    });
};
 
ko.applyBindings(new ViewModel("333-33-3333")); // This makes Knockout get to work