I am working a webpage which will show the search result. After the "search" button was clicked, a search_array should be passed into the template dynamically. How could I dynamically refresh the template after clicking the button? Here is my code:
search_post.html
<div class="form-group">
<label class="control-label" for="title">search by name</label>
<div class="controls">
<input name="SearchName" id="SearchName" type="text" value="" placeholder="enter the name" class="form-control"/>
</div>
</div>
<input type="submit" value="Search" class="btn btn-primary" />
<div id="info" style="display: block; margin-top: 5%">
{{#if show}}
{{#each getInfo}}
{{> postItem}}
{{/each}}
{{/if}}
</div>
search_post.js
var search_array;
Template.postSearch.events({
'click .btn': function() {
search_array = Posts.find({person_name: document.getElementsByName('SearchName')[0].value});
Session.set('show', true);
}
});
Template.postSearch.helpers({
getInfo: function() {
return search_array
},
show: function(){
return Session.get('show');
}
});
Use a Session
variable or ReactiveVar
instead of a normal variable search_array
. That way when you change it the template will automatically update.
Template.postSearch.events({
'click .btn': function () {
let searchName = document.getElementsByName('SearchName')[0].value;
Session.set('searchArray', Posts.find({person_name: searchName}).fetch());
Session.set('show', true);
}
});
Template.postSearch.helpers({
getInfo() {
return Session.get('searchArray');
}
});
You could also just store searchName
in the Session
/ReactiveVar
and do the database query in getInfo
, that way the template will automatically rerender if the database changes.