简体   繁体   中英

JavaScript returns false but still it is submitting

Here is HTML:

<form method="post" action="http://localhost:8080/center/add" onsubmit="return validate()">
  <div class="col-lg-12">
    <table id="myTable">
      <thead>
        <tr>
          <td>
            Start Time
          </td>
          <td>
            End Time
          </td>
          <td>
          </td>
        </tr>
      </thead>
      <tbody>
        <tr class="t-row" title="" style="background: rgb(255, 255, 255);">
          <td>
            <input type="text" onfocus="clearError(this)" class="form-control time-box-width m-t-10px vTimeStart" name="vTimeStart[]" placeholder="Please enter start time in 24 hrs format">
          </td>
          <td>
            <input type="text" onfocus="clearError(this)" class="form-control time-box-width m-t-10px vTimeEnd" name="vTimeEnd[]" placeholder="Please enter end time in 24 hrs format">
          </td>
          <td>
            <input type="button" class="days-btn  m-t-10px" value="Delete">
          </td>
        </tr>
        <tr class="t-row" title="" style="background: rgb(255, 255, 255);">
          <td><input type="text" name="vTimeStart[]" placeholder="Please enter start time in 24 hrs format" onfocus="clearError(this)" class="vTimeStart form-control time-box-width m-t-10px"></td>
          <td><input onfocus="clearError(this)" type="text" name="vTimeEnd[]" placeholder="Please enter end time in 24 hrs format" value="" class="vTimeEnd form-control time-box-width m-t-10px"></td>
          <td><input type="button" value="Delete" class="days-btn  m-t-10px"></td>
        </tr>
      </tbody>
    </table>

    <div class="divide-div"></div>

  </div>
  <div class="modal-footer m-footer" style="border-top: 0;">
    <input class=" days-btn m-t-10px" id="submit" type="submit" value="Submit">
    <input class=" days-btn m-t-10px" id="close-popup" data-dismiss="modal" type="button" value="Close">
  </div>
</form>

JavaScript:

function validate() {

        $('.t-row').each(function(i, obj) {

          var currentStartTimeValue = $('#myTable .vTimeStart').eq(i).val();
          var currentEndTimeValue = $('#myTable .vTimeEnd').eq(i).val();

          if(currentStartTimeValue != '') {
            var v = valdateFormat(currentStartTimeValue);
            alert(v);
            if(!v) {
              alert('Please enter value in HH:MM format.');
              return false;
            }
          }

          if(currentEndTimeValue != '') {
            var v = valdateFormat(currentEndTimeValue);
            if(!v) {
              alert('Please enter value in HH:MM format.');
              return false;
            }
          }

          if(i > 0){
            var previousIndex = i - 1;
            var lastEndTimeValue = $('#myTable .vTimeEnd').eq(previousIndex).val();
            alert(currentStartTimeValue);
            var v = valdateFormat(currentStartTimeValue);
            if(currentStartTimeValue < lastEndTimeValue){
              $(this).attr('title','Current StartTime must be lesser than current EndTime!');
              alert('Current StartTime cannot be lesser than previous EndTime');
              return false;
            }
          }

          if(!currentStartTimeValue){
            var v = valdateFormat(currentStartTimeValue);
            if(!v) {
              alert('Please enter value in HH:MM format.');
              return false;
            }
            $(this).attr('title','Enter value for Start Time!');
            alert('Enter value for Start Time!');
            return false;
          } else if(!currentEndTimeValue){
            var v = valdateFormat(currentEndTimeValue);
            if(!v) {
              alert('Please enter value in HH:MM format.');
              return false;
            }
            $(this).attr('title','Enter value for End Time!');
            alert('Enter value for End Time!');
            return false;
          } else if(currentStartTimeValue >= currentEndTimeValue){
            $(this).attr('title','Current StartTime must be lesser than current EndTime!');
            alert('Current StartTime must be lesser than current EndTime');
            return false;
          }

          if(i === $('.t-row').length - 1) {
            // alert('All good!');
          }

        });

        // return true;

      }

My form is adding dynamically tr , there is one button add row to bottom . When I click on Submit button and validation fails, still it submits the form.

Your validate function doesn't return anything.

The return statements belong to anonymous function passed to .each .

Your return false s are currently inside the each - returning inside the each does not result in the parent function also returning false .

Set a boolean inside the function instead, and then return that after the each is over, eg:

function validate() {
  let valid = true; // <-----------------
  $('.t-row').each(function(i, obj) {

    var currentStartTimeValue = $('#myTable .vTimeStart').eq(i).val();
    var currentEndTimeValue = $('#myTable .vTimeEnd').eq(i).val();

    if(currentStartTimeValue != '') {
      var v = valdateFormat(currentStartTimeValue);
      alert(v);
      if(!v) {
        alert('Please enter value in HH:MM format.');
        valid = false; // <-----------------
        return false;
      }
    }

    if(currentEndTimeValue != '') {
      var v = valdateFormat(currentEndTimeValue);
      if(!v) {
        alert('Please enter value in HH:MM format.');
        valid = false; // <-----------------
        return false;
      }
    }
    // ...
  });
  return valid; // <-----------------
}

You still need to return false inside the each to terminate the loop immediately once a problem is found.

You are returning the value in each loop that would not in turn allow your "validate()" function to return values. You can define a local boolean variable in function and change its value according to your conditions inside loop and return it outside the loop.

See below code

function validate() {
  var returnedValue = true;
  $('.t-row').each(function(i, obj) {

    var currentStartTimeValue = $('#myTable .vTimeStart').eq(i).val();
    var currentEndTimeValue = $('#myTable .vTimeEnd').eq(i).val();

    if(currentStartTimeValue != '') {
      var v = valdateFormat(currentStartTimeValue);
      alert(v);
      if(!v) {
        alert('Please enter value in HH:MM format.');
        returnedValue = false;
      }
    }

    if(currentEndTimeValue != '') {
      var v = valdateFormat(currentEndTimeValue);
      if(!v) {
        alert('Please enter value in HH:MM format.');
        returnedValue = false;
      }
    }

    if(i > 0){
      var previousIndex = i - 1;
      var lastEndTimeValue = $('#myTable .vTimeEnd').eq(previousIndex).val();
      alert(currentStartTimeValue);
      var v = valdateFormat(currentStartTimeValue);
      if(currentStartTimeValue < lastEndTimeValue){
        $(this).attr('title','Current StartTime must be lesser than current EndTime!');
        alert('Current StartTime cannot be lesser than previous EndTime');
        returnedValue = false;
      }
    }

    if(!currentStartTimeValue){
      var v = valdateFormat(currentStartTimeValue);
      if(!v) {
        alert('Please enter value in HH:MM format.');
        returnedValue = false;
      }
      $(this).attr('title','Enter value for Start Time!');
      alert('Enter value for Start Time!');
      return false;
    } else if(!currentEndTimeValue){
      var v = valdateFormat(currentEndTimeValue);
      if(!v) {
        alert('Please enter value in HH:MM format.');
        returnedValue = false;
      }
      $(this).attr('title','Enter value for End Time!');
      alert('Enter value for End Time!');
      returnedValue = false;
    } else if(currentStartTimeValue >= currentEndTimeValue){
      $(this).attr('title','Current StartTime must be lesser than current EndTime!');
      alert('Current StartTime must be lesser than current EndTime');
      returnedValue = false;
    }

    if(i === $('.t-row').length - 1) {
      // alert('All good!');
    }

  });

  return returnedValue;

}```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM