javascript - 验证方法不会在第一次单击按钮时触发

标签 javascript jquery aurelia semantic-ui

我正在使用语义 ui 验证表单,但它仅在我双击按钮而不是单击按钮时有效。这是我的代码:

如何在第一次点击发送按钮时验证表单。

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>

最佳答案

因为这段代码:

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

在第一次点击时将 .form 绑定(bind)到您的 $('.ui.form') 元素。在第二次点击时,您将触发验证,因为它已经绑定(bind)。

如何修复:

// 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>

关于javascript - 验证方法不会在第一次单击按钮时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48767410/

相关文章:

jquery - 悬停时显示在 div 上方

sass - 如何让 Aurelia 处理 scss

javascript - 向 aurelia 项目添加新的 JS 类和模板

javascript - 在 contenteditable div 中的特定位置设置插入符位置

Jquery slidedown显示在其他内容之上

javascript - 带模板的字符串,动态变量

javascript - 32 位或 64 位对 jquery/javascript 有影响吗?

javascript - Aurelia - 集合更改后未创建 repeat.for 中的自定义元素

javascript - 看似良性的 CSS 行导致的 fadeOut "disabled"(jquery bug?)

javascript - Bower 管理的依赖项是否应该 checkin 存储库