Reputation: 1063
I'm trying to build a list of checkboxes by using jQuery.tmpl It'll list an array of items with a checkbox near them, and I want to check some of these checkboxes parametrically...
The template code is:
<ul>
{{each(i,val) Values}}
<li>
<input type="checkbox" {{if $.inArray(i, Default) != -1}} checked="checked"{{/if}}>
<em>${val}</em>
</li>
{{/each}}
</ul>
and the template definition:
<script type="text/javascript">
$(document).ready(function() {
$('#tpl_selector').tmpl({
Default: [1,2],
Values: {
1: 'Item 1',
2: 'Item 2',
3: 'Item 3'
}
}).appendTo('#area');
});
</script>
So the Item 1 and Item 2 should be checked in this case. The list is created with no problem, but {{if $.inArray(i, Default) != -1}} checked="checked"{{/if}}
part is not working.
However, when I replace 'i' with a number, it works:
{{if $.inArray(1, Default) != -1}} checked="checked"{{/if}}
I doesn't make any sense at all... Do you have any suggestions?
Another logic to fill the checkboxes is ok too, like I don't know smt. like a callback function after the rendering completes or else...
Upvotes: 2
Views: 1976
Reputation: 359776
In JavaScript objects, the key is always a string. Your Default
array contains numbers, but the "needle" you're passing in (i
) is a string, so $.inArray
will always return false
,.
Any one of these will work:
Values
a proper array, rather than an object "indexed" by strings containing numbers.
Defaults
an array of strings.
parseInt()
the Values
key (i
) when you pass it to $.inArray()
. I think this is an ugly fix.
Oh, and welcome to Stack Overflow!
Upvotes: 4