Skip to content

Instantly share code, notes, and snippets.

@marucc
Created February 24, 2015 06:51
Show Gist options
  • Save marucc/d38deaba5c2414e90c88 to your computer and use it in GitHub Desktop.
Save marucc/d38deaba5c2414e90c88 to your computer and use it in GitHub Desktop.
KnockoutJSで、Validation通した値でcssの変更を行いたい場合のサンプル
<!DOCTYPE html>
<title>sample</title>
<style>.error { color:red }</style>
<div id="main">
<input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'">
<span data-bind="css: { error: is_error }">*required</span>
<hr>
Name: <span data-bind="text: name"></span>
</div>
<script src="http://knockoutjs.com/downloads/knockout-3.3.0.js"></script>
<script>
function FormViewModel() {
this.name = ko.observable('Name');
this.is_error = ko.pureComputed({
read: function () {
return this.name().replace(/\s/g, '').length == 0;
},
owner: this
})
}
ko.applyBindings(new FormViewModel());
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment