John Higgins
John Higgins

Reputation: 907

Disable form button if data exists

I have a form that performs an ajax database lookup when the user types their email address to make sure that it does not exist and will warn the user if if does.

I would like to be able to disable the button if the email address does exist but not if all ok.

form.html:

<script>
function checkemail()
{
 var email=document.getElementById( "email" ).value;

 if(email)
 {
  $.ajax({
  type: 'post',
  url: 'checkdata.php',
  data: {
   email:email,
  },
  success: function (response) {
   $( '#email_status' ).html(response);
   if(response=="OK")   
   {
    return true;    
   }
   else
   {
    return false;   
   }
  }
  });
 }
 else
 {
  $( '#email_status' ).html("");
  return false;
 }
}
</script>

<input type="email" id="email" name="email" onkeyup="checkemail();" required>
<span id="email_status"></span>
<input type="button" id="submit-button" value="Submit">

checkdata.php:

<?php

error_reporting(E_ALL);

include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");

if(isset($_POST['email']))
{
 $emailId=$_POST['email'];

 $checkdata=" SELECT email FROM membership_main WHERE email='$emailId' ";

 $query = mysqli_query($conn, $checkdata);

 if(mysqli_num_rows($query)>0)
 {
  echo "Email address already exists.";
 }
  else
 {
  echo "OK";
 }
 exit();
}
?>

Upvotes: 1

Views: 1409

Answers (1)

j08691
j08691

Reputation: 207913

Replace:

if(response=="OK") {
    return true;    
} else {
    return false;   
}

With:

if(response=="OK") {
    $('#submit-button').prop('disabled', false)
    return true;    
} else {
    $('#submit-button').prop('disabled', true)
    return false;   
}

You may even be able to remove the return true/false lines as well unless you have some other need for them.

Upvotes: 1

Related Questions