How can I get the value of each separate text box when they’re created within {{#each}}.
This is how I have it so far:
{{#each tester}}
<div class="input-group col-md-12">
<input type="text" id="reply" class="form-control input-sm"/>
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button" id="replyButton">
<i class="fa fa-reply" aria-hidden="true"></i>
</button>
</span>
</div>
{{/each}}
So, let’s say we have 5 tester elements, how would I get the value of one specific text box? Currently, it just gives me the value of the first text box when I get it like this:
'click #replyButton': function(e) {
e.preventDefault();
var content= document.getElementById("reply").value;
}
@simrank You can wrap around your tester element with a wrapper.
Template.templateName.helpers({
'testerWrapper': function (_tester) {
var _output = [];
for (var i = 0; i < _tester.length; i++) {
_output[i] = {};
_output[i].tester = _tester[i];
_output[i].index = i;
}
return _output;
}
});
Then on your template:
{{#each (testerWrapper tester)}}
<div class="input-group col-md-12">
<input type="text" id="reply-{{index}}" class="form-control input-sm"/>
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button" id="replyButton">
<i class="fa fa-reply" aria-hidden="true"></i>
</button>
</span>
</div>
{{/each}}
Your textbox elements will be referenced by rely-1, reply-2…so on
Funny thing is, you are looping the tester element, but I don’t see the tester element being used in the code block you provided.
Hey, that makes sense because then the id would be different for each text box but how would I capture their value when the button is pressed?
Sorry, I do the tester element, I just missed it in my post.
{{#each tester}}
<div class="input-group col-md-12">
<input type="text" id="reply" class="form-control input-sm" value="{{this.name}}"/>
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button" id="replyButton">
<i class="fa fa-reply" aria-hidden="true"></i>
</button>
</span>
</div>
{{/each}}
You can assign the {{index}} to the id of the button as well, so that you can retrieve the corresponding textbox id when a button is clicked. In this case, you can use the class of the button to receive the click event; you cannot use the button id for the click event because every button has a different id.
Okay perfect! I just did that and it worked out perfectly. Thanks so much.
No problem at all, glad that it works out for you.
1 Like