How can i get a easy and clear way that set the first radio button is checked in Handlebars template. tks
template:
<form>
{{#each this}}
<input value="{{value}}" />
{{/each}}
</form>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
expect render:
<form>
<input value="val 1" checked />
<input value="val 2" />
<input value="val 3" />
</form>
thanks all.
It will return the value of the button within the group that is selected, or return a null value if no button in the group is selected. For example, here is the code that will perform the radio button validation: var btn = valButton(form. group1);
Handle radio buttons in PHP When a form has a radio button with a name, you can get the checked radio button by accessing either $_POST or $_GET array, depending on the request method. The filer_has_var() returns true if it finds the radio button name in the INPUT_POST .
{{#each}}
in Handlebars doesn't give you access to the iteration number or anything like that so you can't do it without altering your template and data a little bit:
<form>
{{#each this}}
<input type="radio" value="{{value}}" {{#if sel}}checked="checked"{{/if}} />
{{/each}}
</form>
and then add sel
values to your data:
var tmpl = Handlebars.compile($('#t').html());
var html = tmpl([
{ value: 'val 1', sel: true },
{ value: 'val 2', sel: false },
{ value: 'val 3', sel: false }
]);
Demo: http://jsfiddle.net/ambiguous/27Ywu/
You could of course just set sel: true
on the first element of your data array:
data = [ ... ];
data[0].sel = true;
var html = tmpl(data);
Demo: http://jsfiddle.net/ambiguous/yA5WL/
Alternatively, use jQuery to check the first one after you have the HTML:
// Add the HTML to the DOM...
$('form input:first').prop('checked', true); // Or whatever selector matches your HTML
Demo: http://jsfiddle.net/ambiguous/sPV9D/
Newer versions of Handlebars do give you access to the index:
When looping through items in
each
, you can optionally reference the current loop index via{{@index}}
{{#each array}} {{@index}}: {{this}} {{/each}}
For object iteration, use
{{@key}}
instead:{{#each object}} {{@key}}: {{this}} {{/each}}
So, if you're using the latest Handlebars, you can do something special by using the fact that:
@index
will be zero.That lets you do this:
{{#each this}}
<input type="radio" value="{{value}}" {{#unless @index}}checked="checked"{{/unless}} />
{{/each}}
Demo: http://jsfiddle.net/ambiguous/PHKps/1/
Of course, picking out any other index is harder and leaves you either modifying the input data (as before) or adding some sort of {{#if_eq}}
custom helper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With