2

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...

0

1 Answer 1

4

The problem

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,.

jsfiddle 0

The solutions

Any one of these will work:

  1. Make Values a proper array, rather than an object "indexed" by strings containing numbers.
  2. Make Defaults an array of strings.
  3. parseInt() the Values key (i) when you pass it to $.inArray(). I think this is an ugly fix.

Oh, and welcome to Stack Overflow!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the well explained answer... :) #2 is what I need as the keys matter...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.