【发布时间】:2019-11-26 09:40:03
【问题描述】:
我有一个输入字段和“添加”按钮来存储。单击“添加”按钮时,应创建另一个具有相同类名的输入字段。但在创建之前有一个验证检查。但验证只是第一次。第二次没有验证检查。
以下是我的代码。
$('#add').click(function (e) {
e.preventDefault();
if ($('.js-user-email').val()) {
debugger;
$("#divSpecificToUserError span").text("");
$('#divSpecificToUserError').addClass("d-none");
if (ValidateEmailformat($('.js-user-email').val())) {
//debugger;
$.ajax({
type: "POST",
url: "Stepup.aspx/Exists",
data: JSON.stringify({ emailId: $('.js-user-email').val() }),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response != null && response.d != null) {
var data = response.d;
if (data > 0) {
addDynamicTextboxes();
}
else {
$("#divSpecificToUserError span").text("not a valid user");
$('#divSpecificToUserError').removeClass("d-none");
}
}
},
failure: function (response) {
alert(response.d);
}
});
}
else {
$("#divSpecificToUserError span").text("Please enter email id in valid format");
$('#divSpecificToUserError').removeClass("d-none");
}
}
else {
$("#divSpecificToUserError span").text("No E-mail has been entered ");
$('#divSpecificToUserError').removeClass("d-none");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field form-group form-group-padding">
<label class="col-form-label">User E-mail(s) to Notify:</label>
<input type="text" id="field1" name="userEmail1" class="input form-control js-user-email" placeholder="example@domain.com" autofocus />
<button id="add" class="btn-sm btn-secondary add-more-specific pull-right btn-user-email" title="Add" type="button">+</button>
<div class="col-md-3 d-none alert-danger" id="divSpecificToUserError" style="margin-top: 6px">
<span></span>
</div>
</div>
【问题讨论】:
-
添加html页面,方便我们识别问题。
-
添加了 HTML @chandukomati
-
当您添加点击处理程序
$(".class").click(时,它仅适用于当时存在的具有该类的元素。当您创建一个新的<button class='class;时,已经运行的点击处理程序不适用于这个新元素。您可以在添加新元素时重新添加单击处理程序,或者更轻松地使用事件委托:$(document).on("click", ".class", function...- 请参阅上面的链接了解更多详细信息。 -
为什么不使用点击事件 ID 库。 @ShijoJ
标签: javascript jquery asp.net ajax