John Hadikusumo
John Hadikusumo

Reputation: 1317

Calling Ajax When The Selected Radio Button Has Changed

I am having problem with radio button with knockoutjs. I took me days till now to figure out the solution. You can see my code below:

this is my html tags:

<ul data-bind="foreach:services">
<li>
    <input type="radio" data-bind="value:id,checked:$parent.selectedservice" name="burwood" />
    <span data-bind="text: name"></span>
</li>
</ul>
<br /> 
<button data-bind="click:clicksave">Save</button>

then this is my javascript:

var service = function (id, name) {
        var self = this;
        self.id = ko.observable(id);
        self.name = ko.observable(name);
    };

    var model = function () {
        var self = this;
        self.services = ko.observableArray([]);
        self.addservice = function (service) {
            self.services.push(service);
        };
        self.selectedservice = ko.observable();
        self.selectedservice.subscribe(function () {
            alert('call ajax here.');
        }, null, "change");
        self.clicksave = function () {
            alert(self.selectedservice);
        };
    }


        var m = new model();
        m.addservice(new service('1', 'First'));
        m.addservice(new service('2', 'Second'));
        m.addservice(new service('3', 'Third'));
        m.addservice(new service('4', 'Fourth'));
        m.selectedservice = '1';
        ko.applyBindings(m);

you can visit http://jsfiddle.net/johnhadikusumo/jdApu/ for the real action of the code.

Basically i want an ajax to be called when ever the user has changed their selection the list of radio buttons. If seems self.selectedservice.subscribe is not triggered when its value has changed for some reason.

any help ?

cheers

John

Upvotes: 0

Views: 631

Answers (1)

pax162
pax162

Reputation: 4735

This is the offending line, it removes the observable:

m.selectedservice = '1';

Replace it with:

m.selectedservice('1');

Updated fiddle: http://jsfiddle.net/jdApu/4/

Upvotes: 1

Related Questions