yigames
yigames

Reputation: 185

HTML Knockout radio button to call function

I am using knockout to loop around an array to display a list of radio buttons with labels, and I want it so that whenever a radio button is selected it then calls function onInputChange.

My current code is:

<p data-bind="foreach:properties">
    <br>
    <input name="filter" type="radio" data-bind="checked:$root.sortType, event:$root.onInputChange">
    <label for="filter" data-bind="text:id"></label>
    <br>
</p>

Upvotes: 3

Views: 2256

Answers (2)

4imble
4imble

Reputation: 14416

Something like this?

var model = function() {
  var sortType = ko.observable("Two");
  var properties = ko.observableArray([{id: "One"}, {id: "Two"}, {id: "Three"}]);

  function onInputChange(item) {
    alert("changed to: " + item.id);
  }

  return {
    sortType: sortType,
    properties: properties,
    onInputChange: onInputChange
  };
}

ko.applyBindings(model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<p data-bind="foreach:properties">
  <br>
  <input name="filter" type="radio"
      data-bind="value: id, 
         checked:$parent.sortType, 
         event: {change : $parent.onInputChange }">
  <label for="filter" data-bind="text:id"></label>
  <br>
</p>

Upvotes: 2

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

You should do below

<input name="filter" type="radio" data-bind="checked:$root.sortType, event: { change: $root.onInputChange}">

Upvotes: 2

Related Questions