Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout js radio button click event reset selection

I have bind "checked" and "click" event on a radio button list. But whenever a radio button is clicked, the selection does not stay. I must be doing something really wrong. Really appreciate if you guys can point me to the right direction.

Please see the Fiddle Here

View model:

var viewModel = {
    wantsSpam: ko.observable(true),
    spamFlavor: ko.observable('cherry'),

    click: function(model){
        console.log(model);
    }
};

View:

<input type="radio" name="flavorGroup" value="cherry" 
       data-bind="checked: spamFlavor, click:click" />
like image 513
JenonD Avatar asked Jan 21 '14 05:01

JenonD


3 Answers

From the click event documentation:

By default, Knockout will prevent the click event from taking any default action.
...
However, if you do want to let the default click action proceed, just return truefrom your click handler function.

So your radio button is reset because of your click handler and to fix it you just need to return true at the end:

click: function(){
   alert('Hi');
   return true;
}

Demo JSFiddle.

like image 139
nemesv Avatar answered Nov 20 '22 22:11

nemesv


Basically, your click handler won't end up catching that you want to retain the value.

What is happening is that it is going back to default after you select an item.

Simply try:

return true;

As the only code in your handler.

Fiddle away: http://jsfiddle.net/SinisterSystems/jhHkD/4/

like image 38
Nicholas Hazel Avatar answered Nov 20 '22 23:11

Nicholas Hazel


You just remove the click event or use return true from click event. Because Knockout prevent the click event from taking any default action. This means that if you use the click binding on an a tag (a link), for example, the browser will only call your handler function and will not navigate to the link’s href

var viewModel = {
    wantsSpam: ko.observable(true),
    spamFlavor: ko.observable('cherry'),
    /*click: function(){
      alert('Hi');
    }*/
};

Or

var viewModel = {
    wantsSpam: ko.observable(true),
    spamFlavor: ko.observable('cherry'),
    click: function(){
      alert('Hi');
      return true;
    }
};
like image 5
Linga Avatar answered Nov 20 '22 22:11

Linga