How to add Search using Meteor and Bootstrap?

I am trying to implement a search in my Meteor application. I do not quite understand how this is connected. At this point, I have the following code:

HTML:

<form class="navbar-search pull-left"> <input type="text" class="search-query" placeholder="Search"> </form> 

JS:

 Template.menubar.events({ 'keyup input.search-query': function (evt) { console.log("Keyup value: " + evt.which); if (evt.which === 13) { console.log("Got an Enter keyup"); Session.set("searchQuery", "justATestVar"); } } }); 

I can see the keyup values ​​when I press different keys in the search field, so I know that the event hit. Capturing the enter key also works, but pressing enter forces the site to load, and when I do this:

 Session.get("searchQuery") 

it returns undefined.

I do not know if I am doing this correctly. Essentially, I just want to get the value from the search box, and then use that value to search in my collection. Any help would be appreciated! Thanks.

+4
source share
3 answers

What is likely to happen, your form is submitted when you press enter. Try preventDefault() . Perhaps something like this will work:

 Template.menubar.events({ 'keyup input.search-query': function (evt) { console.log("Keyup value: " + evt.which); if (evt.which === 13) { console.log("Got an Enter keyup"); Session.set("searchQuery", "justATestVar"); } }, 'submit form': function (evt) { evt.preventDefault(); } ... 

You can also try adding evt.preventDefault(); into my keyboard, but I think this is a form post that does this.

+2
source

You really should use the submit button for your search form to avoid breaking accessibility. Using the submit button, the behavior you are looking for is also indicated by default: entering a form when you press the enter key. If you really want to get rid of the submit button, save it in the DOM, but use CSS to hide it.

It is very important to call preventDefault the event that you will receive from the "submit form" handler, if you forget to do this, the page will refresh, disrupting the "Single Application Page" operation (and, by the way, the refresh page will clear your session variables, so you will get undefined value in first of all).

 "submit form":function(event,template){ event.preventDefault(); Session.set("searchQuery",template.find(".search-query").value); } 
+7
source

If someone tries to implement a search function, I recommend the following:

 meteor add matteodem:easy-search 

On the client and server:

 Players = new Meteor.Collection('players'); // name is the field of the documents to search over Players.initEasySearch('name'); 

On the client, do template.html :

 <template name="searchBox"> {{> esInput index="players" placeholder="Search..." }} <ul> {{#esEach index="players"}} <li>Name of the player: {{name}}</li> {{/esEach}} </ul> </template> 

Link

+2
source

Source: https://habr.com/ru/post/1488620/


All Articles