Why are my Knockout Radio buttons failing when ins

2019-07-13 04:48发布

I have a list of radio buttons. I want clicks on the <li> their in to also check the radio button. This all works up until I put a name attribute on the radio elements. Then my code stops working.

Here is what my code looks like:

<ul data-bind="foreach: rows">
    <li data-bind="click: function() { $parent.val($data); }">
        <input type="radio" name="my_radio" data-bind="value: $data, checked: $parent.val" />
        <label data-bind="text: $data"></label>
    </li>
</ul>

Here are two test cases.

Be sure to click on both the radio button and row.

Working: http://jsfiddle.net/Dihedral/HJGxX/2/

Not Working: http://jsfiddle.net/Dihedral/HJGxX/3/

In the second case and when clicking on just the radio, you'll see that the val() observable is being updated, but the UI is not. Anyone know what's going on here, or can see a workaround?

2条回答
倾城 Initia
2楼-- · 2019-07-13 05:16

Having the name attributes all set to the same value makes all these radio buttons part of the same set, and you can only select one of them at once.

Read more about on radio buttons name attribute on www.W3.org

查看更多
forever°为你锁心
3楼-- · 2019-07-13 05:20

The click is not reaching the radio button because knockoutjs returns false from the click handler, preventing the default action to happen (see: note 3). Just return true from the click handler (http://jsfiddle.net/HJGxX/4/):

<li data-bind="click: function() { $parent.val($data); return true; }">
查看更多
登录 后发表回答