0

I have a input field (type=text) on my page. I use Bootstrap and to style the field I use next html code:

<form fole="form">
    <div class="form-group">
        <input type="text" class="form-control" id="add-bookmark" value placeholder="Enter URL">
    </div>
</form>

In the meteor application I have event handler:

Template.new_bookmark.events({

    // add new bookmark
    'keyup #add-bookmark' : function(e,t) {      
      console.log(e.which);
      if(e.which === 13)
      {

When I press any button in the input field I get the key code in the console (as I wish). But if I press the Enter-key the console log have nothing and my page is reloaded.

Looks like the reason of my problem is in the form-tag. If I remove it all works fine. What do I need to do ? Remove the form-tag or prevent the page will be reloaded when I hit the Enter-key ? How can I do it if the answer is second ?

ceth
  • 44,198
  • 62
  • 180
  • 289

1 Answers1

2

The page is not being 'reloaded' it's being submitted and that is the default behaviour when you focus on the form (selecting the input field in the form) and hit enter. How to prevent that, well, add this to your form decliration:

<form name="myForm" onsubmit="return false;"> 

Or if you want to validate the input field before submitting, then you can use a seperate function to do the validation for you:

<form name="myForm" onsubmit="return validate();"> 

function validate()
{
  //pur you validation code here
  return true;
}

As for the key log, actually you will get Enter in your log, but the thing is, when you hit Enter the first action your brwoser will do is to submit the form and therefore will start send a new http reqeust and start transmitting info from the server. When that happens, your browser plugins (Firebug, console etc) will be stoped for a moment and will wait until the new page is loaded. I'm not sure about how much that is accurate, but it's how I understand it.

Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38