Search code examples
meteoriron-router

Form submit event does'nt work as it should(Meteor)


I have a form in meteor, when I submit it, I want to route to a different template. But it doesnt work some how.

The path of form is: localhost:3000/dateForm

input to form is date, month and year of birthday(irrelevant). But when it submit the form(with submit form event in place and having Router.go("/display") present) it just shows "http://localhost:3000/dateform?day=25&month=9&year=1996" in address bar(25, 9, 1996 being the inputs in form) and just shows the same form page.

How do I make the app route to different template on submit event?

The html code in main.html:

<template name="dateFormPage">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
  <link rel="stylesheet" href="https://pingendo.com/assets/bootstrap/bootstrap-4.0.0-alpha.6.css" type="text/css">
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
  <script src="https://pingendo.com/assets/bootstrap/bootstrap-4.0.0-alpha.6.min.js"></script>
  <div class="py-5">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <h1 class="display-1">Enter Your Birthday</h1>
        </div>
      </div>
    </div>
  </div>
  <form>
    <input type="text" placeholder="Day" name="day">
    <input type="text" placeholder="Month(number)" name="month">
    <input type="text" placeholder="Year" name="year">
    <input type="submit" class="btn btn-success">
  </form>
</template>

<template name="display">
  abcderfght
</template>

the code in main.js

Template.dateFormPage.events({
  'submit form': function(event){
    var day=event.target.day.value.parseInt();
    var month=event.target.month.value.parseInt()-1;
    var year=event.target.year.value.parseInt();
    var today=new Date();
    var toDate=today.getDate();
    var toMonth=today.getMonth();
    var toYear=today.getFullYear();

    function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
    }

    var month_diff_raw=monthDiff(new Date(day, month, year), new Date(toDate, toMonth, toYear));

    Session.set("year_diff", month_diff_raw/12);

  },
});

console.log() also doesnt work in event handler.

What's gone wrong in this code?


Solution

  • Very high chance you should simply prevent the form from being actually submitted:

    event.preventDefault();
    

    When user presses your submit button, besides calling your event listener, the browser also submits the form, which default action is to reload the current page.

    This probably explains why your console.log does not seem to work: the console is cleared when the page is reloaded.