验证在jquery中无法正常工作

时间:2017-04-12 12:29:14

标签: javascript jquery

我刚刚创建了一个带有一个按钮的简单输入字段,并且我已经添加了验证。当我单击apply按钮而没有值时,它应该显示错误框,不应该进入if(ack)条件。< br />
在我的代码中显示错误框但是之后它进入if(ack)方法,即使没有值。我做错了什么?

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>

2 个答案:

答案 0 :(得分:2)

var ack更改为每个函数内的ack。全局ack不会替换为each()函数ack。因为您声明两个变量都是一个新的。

function applyLeave() {debugger
     var ack = true
     $('.required').each(function () {

         if ($(this).val() == "") {
             $(this).addClass('inputBorder')
             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>

答案 1 :(得分:1)

在您的代码中,您宣布“确认”。变量两个地方一个是方法级别,另一个是每个函数的本地,而你正在检查方法级别的条件&#39; ack&#39;变量,这个值总是正确的。这就是&#39; if&#39;块正在执行。

var ack = true
$('.required').each(function () {

     if ($(this).val() == "") {
         $(this).addClass('inputBorder')
         var ack = false
     }
})

解决方案您需要将var符号删除为局部变量,如下所示

var ack = true
$('.required').each(function () {

     if ($(this).val() == "") {
         $(this).addClass('inputBorder')
         ack = false
     }
})