j.Doe j.Doe - 3 months ago 17
Javascript Question

why submit on key enter not working

I have a login form where if the input sn on focus and then you press enter it will prompt errors asking you to fill out the fields. But if you fill out both fields, no error comes out and even when you enter the correct credentials and then press enter. nothing happens. the form just gets reset. It works fine if I click the button though.

I am using semantic ui as front-end framework and using its form validation for the errors. Is it because of semantic?

here the link for semantic ui form validation's documentation

Here is my form

<form id="login" class="ui large form" method="post" action="">
<div class="ui stacked secondary segment">
<div class="field">
<div class="ui left icon input">
<i class="user icon"></i>
<input type="text" name="username" placeholder="Nama Pengguna">
</div>
</div>
<div class="field">
<div class="ui left icon input">
<i class="lock icon"></i>
<input type="password" name="password" placeholder="Kata laluan">
</div>
</div>
<input type="submit" name="btn-login" value="Log-masuk" class="ui fluid large teal submit button">
</div>

<div class="ui error message"></div>
</form>


and the javascript for it is

$(document).ready(function() {
$('.ui.form').form({
fields: {
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Sila masukkan Nama Pengguna'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'empty',
prompt: 'Sila masukkan Kata Laluan'
}]
}
}
});
});


Here you can test the login yourself here

Answer

The problem here is that the form has 2 options.
When you hit enter the form submits and when you click the button, your Javascript runs.
You dont want it to submit, you want to trigger the attached JavaScript so remove the form method and the form action
This is a rule in general, you let the form submit handle the submission, or you let the JavaScript handle it.

As you can see from the semantic ui docs the form doesnt have a method or action

<div class="ui horizontal divider">or</div>
<form class="ui form segment">
  <div class="two fields">
    <div class="field">
      <label>Username</label>
      <input placeholder="Username" name="username" type="text">
    </div>
    <div class="field">
      <label>Password</label>
      <input type="password" name="password">
    </div>
  </div>
  <div class="inline field">
    <div class="ui checkbox">
      <input type="checkbox" name="terms">
      <label>I agree to the terms and conditions</label>
    </div>
  </div>
  <div class="ui blue submit button">Submit</div>
  <div class="ui error message"></div>
</form>