xxCodexx
xxCodexx

Reputation: 438

How to have unique name for dynamic elements via handlebars?

I want to have an unique name for input field every time that script is called and the name should not be similar. How can one achieve this ?

<button>Add new field</button>
<script type="text/x-handlebars-template" id="file_name">
  <input type="file" >
</script>
<script type="text/javascript">
    $('button').on('click',function(){
        var template = $('#file-name').html();
        var source = Handlebars.compile(template);
        $('body').append(source());             
    }); 
</script>

Upvotes: 1

Views: 1404

Answers (1)

leguano
leguano

Reputation: 171

You can create an unique id width this function:

<script>
    function create_uid() {
      function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
          .toString(16)
          .substring(1);
      }
      return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
    }
</script>

Use the unique id as variable for your hbs template:

<button>Add new field</button>
<script type="text/x-handlebars-template" id="file_name">
  <input id="{{uid}}" type="file" >
</script>
<script type="text/javascript">
    $('button').on('click',function(){
        var template = $('#file-name').html();

        var data =  {};
        data.uid = create_uid();

        var source = Handlebars.compile(template)(data);

        $('body').append(source());             
    }); 
</script>

If you want: Build this function as helper in Handlebars: http://handlebarsjs.com/builtin_helpers.html

Upvotes: 1

Related Questions