如何使用Meteor动态添加输入控件?

时间:2014-07-21 20:13:20

标签: meteor

我在天气中有一个表单会有条件用户添加他需要的行数。他点击一个按钮,一个输入被添加到另一个下面。 我可以使用jQuery来做到这一点,但我更喜欢使用Meteor的资源。有可能吗?

1 个答案:

答案 0 :(得分:3)

是的,这是我的一个使用underscore package

的应用中的示例

在主模板中:

<template name="ask">
{{#each answerArray}} 
    {{>answer}} 
{{/each}}

<button id="addItem">Add item</button>
</template>

<template name="answer">
<div class="input-group pt10">
    <input class="form-control answer" maxlength="30" placeholder="Answer (max 30 chars)" name="answer" />
    <span class="input-group-btn">
        <button class="btn btn-danger delButton" id="{{id}}" data-id="{{id}}" type="button">Delete</button>
    </span>
</div>
</template> 

在js文件中:

Template.ask.created = function () {
    Session.set('action', 'ask');
    answerArray = [ //adding at least two items but it could also be empty
        {
            id: Random.id(), //using this to give an unique id to the control
            value: ''
        },
        {
            id: Random.id(),
            value: ''
        }
    ];
    Session.set('answerArr', answerArray);
}

点击事件:

Template.ask.events = {
'click #addItem': function () {
    var answerArray = Session.get('answerArr');
    answerArray.push({
        id: Random.id() //just a placeholder, you could put any here
    });
    Session.set('answerArr', answerArray);
}
}

最后帮手:

Template.ask.helpers({
answerArray: function () {
    var answerArray = Session.get("answerArr")

    while (answerArray.length < 2) { //i chose to have it between 2 and 6, you can remove these
        answerArray.push({
            id: Random.id() 
        })
    }
    while (answerArray.length > 6) { // maximum
        answerArray.pop();
    }
    Session.set('answerArr', answerArray);
    return answerArray;
}
}

这将反应性地增加输入数量。之后,如果要处理输入,可以在提交表单事件或按钮单击上执行以下操作:

'click #saveQ': function (e) {
    e.preventDefault();
    var arr = [];
    _.each($('.answer'), function (item) {
        if ($(item).val() != '')
            arr.push({
                answer: $(item).val(), //this you customize for your own purposes
                number: 0
            })
    });

如果您想从页面中删除输入,也可以使用:

Template.answer.events = {
'click .delButton': function (e) {
    var thisId = $(e.target).attr("id");

    var answerArray = Session.get('answerArr');

    var filteredArray = _.filter(answerArray, function (item) {
        return item.id != thisId;
    });

    Session.set('answerArr', filteredArray);
}
}