Return false not stopping submission

I am trying to halt execution if there is an empty input in a form. What is happening is that it goes straight to the ajax call and seems to be totally skipping the return false.

I would also like to remove the css if the input has been completed. Possibly keyup event?.

I would be grateful if someone could point out my error. Many thanks.

jquery code

$(function() {
  $('#editFormProfile').dialog({
    autoOpen: false,
    title: 'Edit a company profile',
    height: 'auto',
    width: '93%',
    modal: true,
    resizable: false,
    //position: { my: 'top', at: 'top+85' },
    modal: true,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "blind",
      duration: 1500
    },
    buttons: [{
      text: "Update",
      "class": 'defaultBtn',
      click: function(e) {
        //e.preventDefault();
        var data = $('#editFormProfile').serialize();
        $('#editFormProfile input[type="text"]').each(function() {
          if ($(this).val() == " " || $(this).val() == "") {
            var ID = $(this).attr("id");
            $(this).css({
              "border": "1px solid red",
              "background": "#FFCECE"
            });
            return false;
          }
        });
        $.ajax({
          type: 'POST',
          url: '/lsorg/users/editProfilesajax.php',
          data: data,
          beforeSend: function() {},
          success: function(data) {
            activity = 'Profile ';
            $("#editFormProfile").trigger("reset");
            $('#editFormProfile').dialog("close");
            showModelEditSuccess(data);
            tableprof.ajax.reload();
          },
          error: function(xhr, status) {
            console.log("Error occured.please try again");
            //$(".text").html(status);
          },
          complete: function() {},
        });
      }
    }, {
      text: "Close",
      "class": 'defaultBtnClose',
      click: function() {
        $(this).dialog("close");
        $("#editFormProfile").trigger("reset");
      }
    }, ],
    close: function() {
      $(".text").html('');
      $("#editFormProfile").trigger("reset");
      $('#editFormProfile').dialog("close");
    }
  });
});

editProfilesajax.php

<?php

$id = $_POST['idprof'];
$code = $_POST['companyprof'];
$name = $_POST['name'];
$addr1 = $_POST['Address1'];
$addr2 = $_POST['Address2'];
$addr3 = $_POST['Address3'];
$town = $_POST['Town'];
$postcode = $_POST['Postcode'];

$user = $_SESSION['ls_name_usr'];
$msg = 'profile has been updated';

$sql = "UPDATE company_com SET idcode_com = '".$code."',name_com = '".$name."',address1_com = '".$addr1."',address2_com = '".$addr2."',address3_com = '".$addr3."',town_com = '".$town."',postcode_com = '".$postcode."' WHERE id_com='".$id."'";
  mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
  mysqli_close($conn);
  echo $msg;

?>

html

<form id="editFormProfile" name="editFormProfile">
  <input class="editInput" id="idprof" name="idprof" type="hidden" value="">
  <div class="form-group-contact">
    <label class="labelStyle-contact" for="companyprof">Company</label> <input class="editInput" id="companyprof" name="companyprof" readonly type="text" value="">
  </div>

  <div class="form-group-contact">
    <label class="labelStyle-contact" for="name">Name <span style="color:red; font-size: 14px;">(Required)</span></label> <input class="editInput" id="name" name="name" type="text" value="">
  </div>

  <div class="form-group-contact">
    <label class="labelStyle-contact" for="Address1">Address1 <span style="color:red; font-size: 14px;">(Required)</span></label> <input class="editInput" id="Address1" name="Address1" type="text" value="">
  </div>

  <div class="form-group-contact">
    <label class="labelStyle-contact" for="Address2">Address2 <span style="color:red; font-size: 14px;">(Required)</span></label> <input class="editInput" id="Address2" name="Address2" type="text" value="">
  </div>

  <div class="form-group-contact">
    <label class="labelStyle-contact" for="Address3">Address3</label> <input class="editInput" id="Address3" name="Address3" type="text" value=""> <!--    <span id="addr3ErrorMsg"></span>-->
  </div>

  <div class="form-group-contact">
    <label class="labelStyle-contact" for="Town">Town <span style="color:red; font-size: 14px;">(Required)</span></label> <input class="editInput" id="Town" name="Town" type="text" value="">
  </div>

  <div class="form-group-contact">
    <label class="labelStyle-contact" for="Postcode">Postcode <span style="color:red; font-size: 14px;">(Required)</span></label> <input class="editInput" id="Postcode" name="Postcode" type="text" value="">
  </div>

  <div class="form-group-contact">
    <div id="addr3ErrorMsg">
    </div>
  </div>

  <div class="text">
  </div>
</form>

Hi @poorbaldrick, you’re just returning from the iterator function here – it’s not possible to break out of the outer event handler function like this. One possible solution would be to set a flag when an input is not valid:

var isValid = true

$('#editFormProfile input[type="text"]').each(function () {
  if (this.value.trim() === '') {
    $(this).css({
      'border': '1px solid red',
      'background': '#FFCECE'
    })
    isValid = false
  }
})

if (!isValid) {
  return;
}

$.ajax(/* ... */)

Or directly reduce the matched elements to its validity value
(which is closer to your original approach, and also a bit more elegant IMHO):

var isValid = $('#editFormProfile input[type="text"]')
  .get()
  .reduce(function (isValid, element) {
    if (element.value.trim() === '') {
      $(element).css({
        'border': '1px solid red',
        'background': '#FFCECE'
      })

      return false
    }

    return isValid
  }, true)

if (!isValid) {
  return;
}

$.ajax(/* ... */)

I think the blur event is what you’re looking for.

1 Like

m3g4p0p

Thank you very much for your swift reply. Both solutions work well, but on the hte negative side from my end, i am not that familiar with jquery yet and shall have to read up on reduce.

lastly, where would I place the blur event so when a user completes the input it removes the red css. Many thanks

Well .reduce() is in fact vanilla JS (see the link above). :-) We just have to call .get() on the jQuery collection to convert it to a regular array first.

Just somewhere at your application root…

$('#editFormProfile input[type="text"]').blur(function () {
  $(this).css({ border: '', background: '' })
})

sorry, where would my application root be. thanks

As you’re using a document ready callback it would be

$(function () {
  // here
})

But I really just meant somewhere where it’s directly getting executed… as opposed to, say, inside the validator function.

Tried that but didn’t work. Would you be able to show me where in my code example you would place it correctly. Many thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.