使用以下代码,我试图验证JavaScript中的输入字段。验证仅需10个字符。进行身份验证时,应该显示一个带有确认消息的模式:
function myFunction() {
var con_code, text;
//getting the field
con_code = document.getElementById("con_code").value;
if ($.trim($('con_code').val()).length == 0) {
text = "Authentication code is not valid";
}
//trigger to the modal if it meets the condition
$(document).ready(function() {
$("#con_code").click(function() {
$("#myModal").modal();
});
});
document.getElementById("error_con_code").innerHTML = text;
}
<div class="container">
<h2>Activate Modal with JavaScript</h2>
<!-- Trigger the modal with a button -->
<div class="form-group">
<label>Confirmation Code.</label>
<input type="text" name="con_code" id="con_code" class="form-control" required="required" placeholder="Enter your Confirmation Code" />
<br> //the error code display
<span id="error_con_code" class="text-danger"></span>
<br> //the authenticate button
<button type="button" class="btn btn-success btn-sm" id="con_code" onclick="myFunction()">Authenticate</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button> //the modal
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
但是,它不对确认码进行身份验证。我该如何解决?
答案 0 :(得分:1)
您在以下位置有错误: if($。trim($('con_code')。val())。length == 0){...}。 应该是$('#con_code')
您还有2个具有相同id =“ con_code”的元素。
请检查以下代码。 我假设您想在输入字段中有10个字符时显示模式。如果规则发生变化,请在以下代码中进行编辑:'if($ .trim(con_code.val())。length!= 10){}'。
$(document).ready(function() {
myFunction();
});
function myFunction() {
$("#con_code_btn").click(function() {
var con_code = $('#con_code');
var error_con_code = $('#error_con_code');
error_con_code.html('');// Remove Previous Error Message(if any);
if ($.trim(con_code.val()).length != 10) {
error_con_code.html("entication code is not valid");
}
else {
$("#myModal").modal();
}
});
}
还请以以下形式将按钮的ID更改为“ con_code_btn”:
<button type="button" class="btn btn-success btn-sm" id="con_code_btn" onclick="myFunction()">Authenticate</button>