我正在使用语义 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/