Search code examples
javascriptractivejs

RactiveJS multiple radios with same name attr


I've been having some trouble with my web application using RactiveJS and radio buttons.

I have an array of "event" objects which contains an attribute with a value of either 1 or 0. Then for each event i render a component called Event and pass in the event object. Then in the template i do something like this to display the initial state of the radio buttons:

<script id="Event" type="x-template">
    <input type="radio" value="1" name="{{evt.val}}" /> 1<br />
    <input type="radio" value="0" name="{{evt.val}}" /> 0<br /><br />
</script>

However since i've got multiple events the name attribute is duplicated in many places and are seen as one group of radio buttons, instead of multiple groups. I know that this is browser behavior but it makes it very inconvenient when ractive binds on the name attribute. Is there any way to work around this? The data comes from a server and may differ from every event so it's very troublesome.

Please look here at this fiddle which demonstrates the problem:

http://jsfiddle.net/5x03cexd/4/

Kind regards,


Solution

  • Although I still think it's a rather bad choice to use the name attribute of radio inputs to hold the currently selected value from the group, it turns out it is by design. There was even a bug report about that: https://github.com/ractivejs/ractive/issues/1937

    The issue is already closed, they mention two workarounds to make it work, the simplest is to wrap your radio inputs in form elements to scope them corectly.

    Ractive.components.Event = Ractive.extend({
       template: '#Event'
    });
    
    new Ractive({
    	el: 'body',
      template: '#Calendar',
      data: function () {
      	return {
        	events: [{val: 1}, {val: 0}, {val: 1}, {val: 1}, {val: 0}]
        };
      }
    });
    <script src="http://cdn.ractivejs.org/0.7.3/ractive.js"></script>
    
    <script id="Calendar" type="x-template">
        {{#each events}}
        	<Event evt={{.}} />
        {{/each}}<br /><br />
        
        Only one element get's checked because the name attribute is duplicated...
    </script>
    
    <script id="Event" type="x-template">
        <form>
          <input type="radio" value="1" name="{{evt.val}}" /> 1<br />
          <input type="radio" value="0" name="{{evt.val}}" /> 0<br /><br />
        </form>
    </script>

    Fiddle