qts
qts

Reputation: 1044

Handlebars & Jquery: Dynamically generated ids

I am generating a dynamic form and button on a handlebars page.

The original handlebars code is this:

{{#each record}}
    <input class="form-control" type="text" id="comment" value={{comment}}> 
    <button class="btn small btn-success" id="btn-savecomment">SAVE COMMENT</button>
{{/each}}

and I have a jquery script to save the contents of the form when each button is pressed:

$(document).ready (
    function() {
        $(document).on('click','#savecomment',function(event){
            // save id: comment to record
    );

The purpose is to allow the user to type in a comment and then save it to each record.

However how can I ensure the button identifies the right input form when looking the comment? When I click on a particular button it only retrieves the comment from the first record because all of them have identical ids.

Appreciate the help!

Upvotes: 1

Views: 1637

Answers (3)

Pete TNT
Pete TNT

Reputation: 8403

Well, you could dynamically generate the IDs, but most likely you should just should just be using classes or data-values (or similar) that are a better fit:

{{#each record}}
    <input class="form-control" type="text" data-comment={{@index}} value={{comment}}> 
    <button class="btn small btn-success" data-trigger="save">SAVE COMMENT</button>
{{/each}} 

$(document).on("click", "[data-trigger='save']", function (evt) {
  var commentID = $(this).prev().data("comment"); //index number, can be pretty much anything
});

Upvotes: 1

K K
K K

Reputation: 18099

You can not have identical id on different element. That's why your code isn't working. Give each element a different id. You may use {{@index}} to get the current iteration count and then use it in the id to generate a dynamic id i.e:

<input class="form-control" type="text" id="comment_{{@index}}" value={{comment}}>

You should do the same for the button as well. In your jQuery code, you can then access the input using prev() method

You can then access it using jquery. Or you may also use class instead of id. That would be better.

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167212

What you are doing is actually wrong. As you know already, IDs should not be duplicated. You should be using something like this:

{{#each record}}
    <input class="form-control" type="text" id="comment" value={{comment}}> 
    <button class="btn small btn-success btn-savecomment" id="btn-savecomment-{{@index}}">SAVE COMMENT</button>
{{/each}}

And the next one is in the jQuery:

$(document).ready (function() {
    $(document).on('click', '.btn-savecomment', function (event) {
        // save id: comment to record
    });
});

Upvotes: 0

Related Questions