Nithin Viswanathan
Nithin Viswanathan

Reputation: 3283

How to set json value in knockout js?

I have got a task to do knockout.js.But I can't create the textbox value as json object. I have a model student with fields name and age.For creating new student i can't set the value as json object. newlist.html.erb

 <script>
$(document).ready(function() {
var viewModel = {
    firstName: ko.observable(),

    _age: ko.observable(),
    validationMessage: ko.observable()
};
var self = this;
self.save = function() {
        var dataToSave =firstName: ko.observable();
                        _age: ko.observable();
                        alert("Could now send this to server: " + JSON.stringify(viewModel));
                        }
viewModel.Age = ko.dependentObservable({
    read: viewModel._age,
    write: function (value) {
        if (!isNaN(value)) {
            this._age(value);
            this.validationMessage("");
        }
        else {
            this.validationMessage("Age must be a number!");
        }
    },


    owner: viewModel

});

ko.applyBindings(viewModel);
});
</script>
<h1>Testing</h1>
Name: <input type="text" data-bind="
                                    value: firstName,
                                    valueUpdate : 'afterkeydown'
                                    "/>
<br />

Age: <input type="text" data-bind="value: Age, valueUpdate : 'afterkeydown'" />



<Br /> 
<span data-bind="text: validationMessage" style="color:Red"></span>

<Br />
<button data-bind='click: save'>Submit</button>
<Br />

But it shows some error. How can I create a json object?

Upvotes: 0

Views: 730

Answers (1)

Ilya
Ilya

Reputation: 29663

You can convert model to json in next way

var dataToSave = {
                    firstName: viewModel.firstName(),
                    _age: viewModel._age()
                 }  

here you task is resolved: Solution

Upvotes: 1

Related Questions