我剛創建了一個按鈕的簡單輸入字段,並添加了對此的驗證。當我單擊不帶值的apply
按鈕時,它應顯示錯誤框,並且不應在if(ack)
條件內進入。
在我的代碼錯誤框正在顯示,但之後它進入if(ack)
方法,即使沒有values.What我做錯了嗎?驗證在jquery中無法正常工作
function applyLeave() {
debugger
var ack = true
$('.required').each(function() {
if ($(this).val() == '') {
$(this).addClass('inputBorder')
var ack = false
}
})
if (ack) {
var newLeaveDetails = {};
newLeaveDetails = {
a: $('#levType').val(),
b: $('#levFrom').val(),
c: $('#levTo').val(),
d: $('#levDuration').val(),
e: $('#uploadDoc').files[0],
g: $('#LevReason').val(),
}
console.log(newLeaveDetails)
var ajaxObj = JSON.stringify({
LeaveDetails: newLeaveDetails
});
console.log(ajaxObj)
$.ajax({
type: 'POST',
url: '',
async: true,
data: ajaxObj,
contentType: 'application/json',
success: function() {
$(".success").html("Leave applied successfully!");
$('.success').show();
window.setTimeout(function() {
window.location.href = '/leave/employeeleavelist'
}, 1000);
},
error: function() {
alert("Try Again")
}
})
}
}
.inputBorder {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="row border" id="applyLeave">
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label class="col-xs-12">Leave Type<span class="requiredField">*</span></label>
<select type="text" id="levType" class="col-xs-12 form-control required"></select>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label class="col-xs-12">Available/Taken</label>
<input type="text" id="levTaken" class="col-xs-12 form-control levTaken" readonly="readonly">
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label class="col-xs-12">Date From<span class="requiredField">*</span></label>
<input type="date" id="levFrom" class="col-xs-12 form-control levFrom required">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label class="col-xs-12">Date To<span class="requiredField">*</span></label>
<input type="date" id="levTo" class="col-xs-12 form-control levTo required">
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label class="col-xs-12">Duration(Days)</label>
<input type="text" id="levDuration" class="col-xs-12 form-control levDuration" readonly="readonly">
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<label class="col-xs-12">Supporting Document</label>
<input type="file" class="form-control col-lg-2 col-md-2 col-sm-2" id="uploadDoc">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 ">
<label class="col-xs-12">Reason<span class="requiredField">*</span></label>
<textarea id="LevReason" class="col-xs-12 form-control addCc required" rows="2"></textarea>
</div>
</div>
<div class="row pull-right btnMarginTop">
<button class="btn btn-primary applyLevBtn" onclick="applyLeave()">Apply</button>
</div>
</section>
您在每個循環中定義新的變量。只要刪除'var'。 – Oen44