Jules
Jules

Reputation: 275

Jquery preventDefault not workign after field validation

The following code is meant to validate an input is not blankt, and then submit the form via Ajax. It work works fine when the validation is removed, but when it is in place the preventDefault does not appear to be effective.

$(document).on("keydown", "input[class='p']", function(e){

  if (e.which == 13) {

    if($(this).val() == ''){        \\\\ Validation
        alert('The Field Empty');
        return false;
        }

  e.preventDefault();  

  var theData = $("form").serializeArray();
  var parentDiv = '#theDiv';

  $.ajax({
  type: "POST",
  url: "functions.php",
  data: theData,
  cache: false,
  success: function(data){
     $(parentDiv).html(data);
          }
       })
     }
  });

I have tried moving the preventDefault to above the validation but this doesn't work either. Can anyone spot what I am doing wrong?

Thanks

Jules

EDIT : Edited to correct an error with the validation checking procedure which is not relevant to the problem being discussed.

Upvotes: 0

Views: 61

Answers (2)

Jules
Jules

Reputation: 275

Credit and thanks for this solution goes to TCHdvlp...

$(document).keypress(function(event){
    if (event.keyCode == 10 || event.keyCode == 13) 
        event.preventDefault();
  });

$(document).on("keydown", "input[class='p']", function(e){

    if (e.which == 13) {

if($(this).val() == ''){ 
    alert('Field Empty');
    return false;

} 


var theData = $("form").serializeArray();
  var parentDiv = '#theDiv';

  $.ajax({
  type: "POST",
  url: "functions.php",
  data: theData,
  cache: false,
  success: function(data){
     $(parentDiv).html(data);
      }
       })


   }
    });

Upvotes: 0

TCHdvlp
TCHdvlp

Reputation: 1334

$(this).val('') You should have put $(this).val() != '' or you are not testing but affecting !!! That's why your validation must be breaking your code.

Upvotes: 1

Related Questions