Rohit Kharkwal
Rohit Kharkwal

Reputation: 11

Validate method is not firing at first click of a button

I am validating a form using semantic ui but it is only working when I double click a button rather than single click. Here is my code:

How to validate form at first click of send button.

validate() {
  $('.ui.form')
    .form({
      inline: false,
      on: 'blur',
      fields: {
        to: {
          identifier: 'to',
          rules: [{
            type: 'email',
            prompt: 'Please enter email address'
          }]
        },
        comments: {
          identifier: 'comments',
          rules: [{
            type: 'empty',
            prompt: 'Please enter comments'
          }]
        }
      },
      onSuccess: function(event) {
        $.ajax({
          type: "POST",
          url: "/api/controller",
          cache: false,
          async: false,
          success: function(data) {

          },
          error: function(err) {
            console.log(err + "err");
          }
        });
        event.preventDefault();
      },
      onFailure: function(event) {
        alert("fail");
        event.preventDefault();
      }
    });
}
<div class="ui container right aligned">
  <button id="btnSuccess" class="ui primary submit button form" 
    click.delegate="validate()">Send</button>
</div>

Upvotes: 1

Views: 695

Answers (1)

Michal
Michal

Reputation: 5226

Because this code snippet:

validate() {
  $('.ui.form')
}

On the first click binds .form to your $('.ui.form') element. On second click you fire the validation because it is already bound.

How to fix it:

// This will add event listetner itself. You don't need to call anything
$( document ).ready(function() {
  $('.ui.form')
    .form({
      inline: false,
      on: 'blur',
      fields: {
        to: {
          identifier: 'to',
          rules: [{
            type: 'email',
            prompt: 'Please enter email address'
          }]
        },
        comments: {
          identifier: 'comments',
          rules: [{
            type: 'empty',
            prompt: 'Please enter comments'
          }]
        }
      },
      onSuccess: function(event) {
        $.ajax({
          type: "POST",
          url: "/api/controller",
          cache: false,
          async: false,
          success: function(data) {

          },
          error: function(err) {
            console.log(err + "err");
          }
        });
        event.preventDefault();
      },
      onFailure: function(event) {
        alert("fail");
        event.preventDefault();
      }
    });
});

<!-- Notice that i removed the onClick handler -->
<div class="ui container right aligned">
  <button id="btnSuccess" class="ui primary submit button form">Send</button>
</div>

Upvotes: 1

Related Questions