Reputation: 3083
So I'm creating a simple poll app. I have a form that has 3 fields, for 3 answers for a question of the poll. What I would like to do is create a button so that I can create more fields dynamically when I need them.
But I'm confused about how to do this
<template name="pollForm">
<form class="new-poll">
<div class="form-group">
<label>Question</label>
<input type="text" name="question" placeholder="Your Question">
</div>
<div class="form-group">
<label>Choice #1</label>
<input type="text" name="choice1" placeholder="Choice #1">
</div>
<div class="form-group">
<label>Choice #2</label>
<input type="text" name="choice2" placeholder="Choice #2">
</div>
<div class="form-group">
<label>Choice #3</label>
<input type="text" name="choice3" placeholder="Choice #3">
</div>
</form>
</template>
How can I modify the HTML of the template so I can add more fields?
Upvotes: 0
Views: 48
Reputation: 5156
You could register a click event and append new HTML elements with JavaScript or jQuery:
$('<div>').attr('class', 'form-group').insertBefore('#add-choice');
$('<label>').text('Choice #1').appendTo('form div.form-group:last');
$('<input>').attr('type', 'text').attr('name', 'choice1').attr('placeholder', 'Choice 1').appendTo('form div.form-group:last');
Another approach would be to use a local (client-side) Meteor collection and insert documents when clicking the button:
Choices = new Mongo.Collection(null);
if (Meteor.isClient) {
Template.pollForm.events({
'click #add-choice': function () {
Choices.insert({'label': 'Choice #123', 'placeholder': 'Choice #123', 'name': "choice123"});
}
});
Template.pollForm.helpers({
choices: () => Choices.find()
});
Template.pollForm.onRendered(function () {
Choices.insert({'label': 'Choice #1', 'placeholder': 'Choice #1', 'name': "choice1"});
Choices.insert({'label': 'Choice #2', 'placeholder': 'Choice #2', 'name': "choice2"});
Choices.insert({'label': 'Choice #3', 'placeholder': 'Choice #3', 'name': "choice3"});
});
}
<template name="pollForm">
<form class="new-poll">
<div class="form-group">
<label>Question</label>
<input type="text" name="question" placeholder="Your Question">
</div>
{{#each choices}}
<div class="form-group">
<label>{{label}}</label>
<input type="text" name="{{name}}" placeholder="{{placeholder}}">
</div>
{{/each}}
<button type="button" id="add-choice">Add choice</button>
</form>
</template>
Upvotes: 1