if user want to submit their form, they have to checked the terma and condition box first.
so where should i add the code?
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = "";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</form>
</fieldset>
</form>
</div>
</body>
</html>
and so here is my userdetail.php to get user data...
<?php
session_start();
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
$email = $_SESSION['email'];
$postalAddress = $_SESSION['postalAddress'];
$landLineTelNo = $_SESSION['landLineTelNo'];
$mobileTelNo = $_SESSION['mobileTelNo'];
$sendMethod = $_SESSION['sendMethod'];
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
if($_SESSION['postalAddress']==NULL)
{echo "<p>postalAddress:NULL</p>";}
else {echo "<p>PostalAddress : $postalAddress </p>";}
if($_SESSION['email']==NULL)
{echo "<p>email:NULL<p/>";}
else {echo "<p>email : $email</p>";}
if($_SESSION['landLineTelNo']==NULL)
{echo "<p>landLineTelNo:NULL<p/>";}
else {echo "<p>landLineTelNo : $landLineTelNo </p>";}
if($_SESSION['mobileTelNo']==NULL)
{echo "<p>mobileTelNo:NULL<p/>";}
else {echo "<p>mobileTelNo : $mobileTelNo </p>";}
echo "<p>sendMethod : $sendMethod </p>";
?>
i need the term and condition check box to be checked else use cannot submit the form....
REMEMBER! Using javascript will just make it easy for user.It prevents loading another page to display error. STILL if a browser has javascript turned of it will pass the checked Terms without even checking it. so you should Always check it serverside (PHP) and use javascript for users ease.
in your HTML:
<form id="userdetail" ....>
...
<input type="checkbox" name="terms" id="terms" value="accepted" />
...
</form>
then in your javascript:
Pure JS:
document.getElementById('userdetail').addEventListener('submit', function(event){
if(document.getElementById('terms').checked == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
Using JQuery (jquery.com)
$('#userdetail').submit(function(event){
if($('#terms').is(':checked') == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
and in your PHP to check if it is checked you should use
if(isset($_POST['terms']) && $_POST['terms'] == 'accepted') {
// Continue Registring
} else {
// Display Error
}
Instead of submit you do:
<input type="button" onclick="javascript:myFunction()" Value="Submit">
And then the javascript function:
function myFunction() {
if(document.getElementById("terms").checked == true){
document.getElementById("userdetail").submit();
}
else{
alert("You have to agree on terms and conditions");
}
}
In Jquery you can do like below:
<script>
$('#userdetail').submit(function(){
if($('#terms').is(':checked'))
{
return true;
}
else
{
return false;
}
});
</script>
Replace the part of html with the given html in answer and add the function below to you script...
function verify_terms()
{
if (!$('#terms').is(':checked'))
{
alert('Please agree terms and conditions');
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" onclick="return verify_terms();" value="submit" />
Related
I want to create a form where the submit button is disabled until the form is ready to be submitted. Not only does the form need to be filled in, but certain parameters need to be met. Passwords must match. Email must be valid and not already be in the database. A radio button must be selected. How can I send the values from all inputs at the same time on every upkey.
Here's my index.php file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
function validate_form(value){
$.post("validate_form.php",{first_name:value},function(data){
if (data=="Available"){
document.getElementById("mySubmit").disabled = false;
} else {
document.getElementById("mySubmit").disabled = true;
}
});
};
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="first_name" placeholder="First Name" onkeyup="validate_form(first_name.value)"><br>
<input type="text" name="last_name" placeholder="Last Name"><br>
<input type="text" name="email" placeholder="Email"><br>
<input type="password" name="password" placeholder="Password"><br>
<input type="password" name="password_repeat" placeholder="Re-enter Password"><br>
<input type="radio" name="choice" value="Y" id="yes">Yes
<input type="radio" name="choice" value="N" id="no">No
<br>
<input type="submit" name="submit" value="Sign Up" disabled id="mySubmit">
</form>
</body>
</html>
and here's my validate_form.php file
<?php
$first_name = "";
$last_name = "";
$email = "";
$password = "";
$password_repeat = "";
$answer = "";
$go = array(0,0,0,0,0);
if(isset($_POST['first_name'])){$first_name = $_POST['first_name'];}
if(isset($_POST['last_name'])){$last_name = $_POST['last_name'];}
if(isset($_POST['email'])){$email = $_POST['email'];}
if(isset($_POST['password'])){$password = $_POST['password'];}
if(isset($_POST['password_repeat'])){$password_repeat = $_POST['password_repeat'];}
if(isset($_POST['choice'])){$answer = $_POST['answer'];}
//Does email already exist in database
mysql_connect("localhost", "root", "password") or die (mysql_error ());
mysql_select_db("database") or die(mysql_error());
$strSQL = "SELECT * FROM users";
$loop = mysql_query($strSQL);
$email_exists = 0;
while($row = mysql_fetch_array($loop)) {
if($row['email'] == $email){
$email_exists = 1;
}
}
//Is email valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$email_valid = 1;
} else {
$email_valid = 0;
}
//Check each parameter
if(strlen($first_name) > 0){
$go[0] = 1;
}
if(strlen($last_name) > 0){
$go[1] = 1;
}
if($email_exists != 1 and $email_valid == 1){
$go[2] = 1;
}
if(strlen($password) > 6 and $password == $password_repeat){
$go[3] = 1;
}
if($answer != ""){
$go[4] = 1;
}
if(array_sum($go) == 5){
echo "Available";
} else {
echo "Form is not viable";
}
?>
I currently have it send $first_name to validate_form.php, but I'm not sure how to send all variables at once. Any help would be awesome.
Trying to get my customer registration page for a hotel database to validate the input with javascript then php, and update the database with the new customers info and redirect them to the correct login page (customerlogin).
When i click submit, state, telephone, country, suburb, title go blank and the other feilds remain with the info entered.
Please help thanks
<?php
require_once("dbconn.php");
$username = $pwrd = $repwrd = $gname = $sname = $addr = $suburb = $state = $ptcode = $mobile = $email = "";
$usernameErr = $pwrdErr = $repwrdErr = $gnameErr = $snameErr = $addrErr = $suburbErr = $stateErr = $ptcodeErr = $mobileErr = $emailErr = "";
//when the form is being submitted
if (isset($_POST["submit"]))
{
$username = mysqli_real_escape_string($dbConn, $_POST["uname"]);
if (empty($username))
$usernameErr = '<span class="error">Please enter a Unique ID</span>';
else {
$Npattern = "/^[a-zA-Z0-9]{1,20}+$/";
if (!preg_match($Npattern, $username))
{
$usernameErr = '<span class="error">Username already exists!</span>';
}
}
$pwrd = mysqli_real_escape_string($dbConn, $_POST["pword"]);
if (empty($pwrd))
$pwrdErr = '<span class="error">Please enter a password</span>';
else {
$PWpattern = "/^[a-zA-Z0-9]{6,20}+$/";
if ( !preg_match($PWpattern, $pwrd))
{
$pwrdErr = '<span class="error">Password must be minimum of 6 characters</span>';
}
}
$repwrd = mysqli_real_escape_string($dbConn, $_POST["pword2"]);
if ( empty($repwrd))
$repwrdErr = '<span class="error">Please ensure passwords match</span>';
else {
$pwrd = mysqli_real_escape_string($dbConn, $_POST["pword"]);
if (! $repwrd == $pwrd )
{
$repwrdErr = '<span class="error">Passwords do not match</span>';
}
}
$gname = mysqli_real_escape_string($dbConn, $_POST["FName"]);
if (empty($gname))
$gnameErr = '<span class="error">Please enter your First Name</span>';
else {
$Gpattern = "/^[a-zA-Z .\-]{1,20}+$/";
if ( !preg_match($Gpattern, $gname))
{
$gnameErr = '<span class="error">First Name can only contain alphabetical letters, spaces, hyphens and apostrophe';
$gnameErr .= 'it also must not exceed 20 characters</span>';
}
}
$sname = mysqli_real_escape_string($dbConn, $_POST["LName"]);
if (empty($sname))
$snameErr = '<span class="error">Please enter Last Name</span>';
else {
$Fpattern = "/^[a-zA-Z .\-]{1,20}+$/";
if ( !preg_match($Fpattern, $sname))
{
$snameErr = '<span class="error">Family Name can only contain alphabetical letters, spaces, hyphens and apostrophe';
$snameErr .= 'it also must not exceed 20 characters</span>';
}
}
$addr = mysqli_real_escape_string($dbConn, $_POST["add"]);
if (empty($addr))
$addrErr = '<span class="error">Please enter Address</span>';
else {
if (strlen($addr) > 40 )
{
$addrErr = '<span class="error">Your Address must not exceed 40 characters long </span>';
}
}
$state = mysqli_real_escape_string($dbConn, $_POST["state"]);
if ($state == "--" )
$stateErr = '<span class="error"> Please enter state</span>';
$ptcode = mysqli_real_escape_string($dbConn, $_POST["pcode"]);
if (empty($ptcode))
$ptcodeErr = '<span class="error">Please enter postcode</span>';
else {
$pcPattern = "/^[0-9]{4}$/";
if (!preg_match($pcPattern,$ptcode))
$ptcodeErr = '<span class="error">Postcode must be 4 digits</span>';
}
$mobile = mysqli_real_escape_string($dbConn, $_POST["mobile"]);
if (empty($mobile))
$mobileErr = '<span class="error">Please enter mobile number</span>';
else {
$Mobilepattern = "/^04?\d{8}$/";
if (!preg_match($Mobilepattern, $mobile))
$mobileErr = '<span class="error">Mobile number must be 10 digits</span>';
}
$email = mysqli_real_escape_string($dbConn, $_POST["email"]);
if (empty($email))
$emailErr = '<span class="error">Please Enter email address</span>';
else {
if ( filter_var($email,FILTER_VALIDATE_EMAIL))
{
$emailErr = '<span class="error">Email not Valid</span>';
}
}
}
else if (isset($_POST["reset"]))
{
unset($_POST["username"]);
unset($_POST["password"]);
unset($_POST["repassword"]);
unset($_POST["gname"]);
unset($_POST["sname"]);
unset($_POST["address"]);
unset($_POST["state"]);
unset($_POST["postcode"]);
unset($_POST["mobile"]);
unset($_POST["email"]);
unset($_POST[""]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" language="javascript" >
function validateUsername(uname)
{
var uname = document.getElementById("uname").value;
if (uname.length < 21) {
return true;
} else {
Alert("Please choose a username with a max of 20 characters");
return false;
}
}
function validatePword(input)
{
var pword = document.getElementById("pword").value;
if (pword.length > 6) {
return true;
}
else
{
alert("Please choose a Password between 6 and 20 characters");
return false;
}
if (pword.length < 20) {
return true;
} else {
alert("Please choose a Password between 6 and 20 characters");
}
}
function confirmPword(input)
{
var pword = document.getElementById("pword").value;
var pword2 = document.getElementById("pword2").value;
if (pword2 == pword){
return true;
}
else
{
alert("Passwords do not match, please retype password in both feilds.");
}
}
function validateName(txt) {
var letters = /^[A-Za-z-']+$/;
if (txt.value.match(letters)) {
return true;
} else {
alert("Invalid Characters Entered for Name")
return false;
}
}
function validateAdd(input) {
var add = document.getElementById("add").value;
if (add.length < 41) {
return true;
} else {
alert("Address must not be more then 40 characters");
}
}
function validatePcode(input) {
var pcode = document.getElementById("pcode").value;
var numbers = "123456789";
if (pcode.length < 4) {
alert("Postcode must be 4 digits")
}
else {
if (pcode.value.match(numbers)){
return true;
}
}
}
function validatePhone(input) {
var phoneNo = /^\d{10}$/;
if (input.value.match(phoneNo)) {
return true;
} else {
alert("Phone number must be in the format of 04xxxxxxxx");
}
}
function validateEmail(input) {
var email = input.value;
if (email.indexOf("#") > -1 && email.indexOf(".") > -1) {
return true;
} else {
alert("Please enter a valid email address");
return false;
}
}
</script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<form id="regForm" name="regForm" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return confirmPword();">
<div id="header">
<h1>Western Sydney Hotel</h1>
</div>
<h1>Register as a User</h1>
<p> Please fill out the form below to register for the hotel website. </p>
<hr>
<h2>Account Details</h2>
<b>Username</b>
<input type= "text" name="uname" id="uname" size="20" maxlength="20" onblur="validateUsername(this);" value="<?php echo htmlspecialchars($username); ?>">
<br><br>
<b>Password</b>
<input type= "password" name="pword" id="pword" size="20" maxlength="20" min="6" onblur="validatePword(this);" value="<?php echo htmlspecialchars($pwrd); ?>">
<b>Retype password</b>
<input type= "password" name="pword2" id="pword2" size="20" maxlength="20" min="6" value="<?php echo htmlspecialchars($repwrd); ?>">
<br>
<hr>
<h2>Personal Details</h2>
<p>
<b>Title:</b>
<br>
<select name="Title" required>
<option value=" "></option>
<option value="Dr">Dr</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
</select>
</p>
<p><b>First Name:</b><br> <input type= "text" name="FName" id="FName" size="20" maxlength="20" onblur="validateName(this);" value="<?php echo htmlspecialchars($gname); ?>" /></p>
<p><b>Family Name:</b><br> <input type="text" name="LName" id="LName" size="20" maxlength="20" onblur="validateName(this);" value="<?php echo htmlspecialchars($sname); ?>" /></p>
<hr>
<h2>Contact Details</h2>
<p><b>Street Address:</b><br> <input type="Text" Name="add" id="add" size="40" maxlength="40" onblur="validateAdd(this);" value="<?php echo htmlspecialchars($addr); ?>" /></p>
<p><b>Suburb:</b><br> <input type="text" name ="Suburb" value="<?php echo htmlspecialchars($suburb); ?>" /></p>
<p><b>State:</b><br> <select name ="state" id="state" value="<?php echo htmlspecialchars($state); ?>" >
<option value=" "> </option>
<option value="nsw"> NSW </option>
<option value="wa"> WA </option>
<option value="sa"> SA </option>
<option value="vic"> VIC </option>
<option value="qld"> QLD </option>
<option value="nt"> NT </option>
<option value="act"> ACT </option>
</p>
</select>
<br>
<p><b>Country:</b><br> <input type="text" name ="country" /></p>
<p><b>Postcode:</b> <br><input type="Text" size="4" maxlength="4" name="pcode" id="pcode" onblur="validatePostcode(this);" value="<?php echo htmlspecialchars($ptcode); ?>"/> </p>
<p><b>Telephone:</b><br> <input type="Tel" name="Telephone" /></p>
<p><b>Mobile:</b><br> <input type="text" name="mobile" id="mobile" onblur="validatePhone(this);" value="<?php echo htmlspecialchars($mobile); ?>" /></p>
<p><b>Email:</b><br> <input type="Email" name="email" maxlength="40" onblur="validateEmail(this);" value="<?php echo htmlspecialchars($email); ?>" /></p>
<br>
<hr>
<input type="Submit" name="submit" value="Submit"/>
<input type="Reset" name ="reset" value="Reset"/>
<br>
<br>
<div id="footer">
Copyright © Western Sydney Hotels
</div>
</form>
<?php
require_once("dbconn.php");
if (isset($_POST["submit"]) && strlen($usernameErr)==0 && strlen($pwrdErr)==0 && strlen($repwrdErr)==0 && strlen($gnameErr)==0 && strlen($snameErr)==0
&& strlen($addrErr)==0 && strlen($stateErr)==0 && strlen($ptcodeErr)==0 && strlen($mobileErr)==0 && strlen($emailErr)==0)
{
$sql = "INSERT INTO customers(username, password, gname, sname, address, state, postcode, mobile, email)
VALUES ('$username', '$pwrd', '$gname', '$sname', '$addr', '$state', '$ptcode', '$mobile', '$email')";
if (mysqli_query($dbConn, $sql))
{
echo "Registration for Western Sydney Hotels complete";
header("location: customerlogin.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbConn);
}
}
mysqli_close($dbConn);
die();
?>
</body>
</HTML>
I have searched but I get info about how to disable submit button till all fields are completed....
I have following form where some fields are required and some are optional.
I want to disable submit button till required fields are completed.
sample code of form :
<form name="registration_form" id="registration_form" action="nextaction.php" method="post" enctype="multipart/form-data" >
Name : <input type="text" id="name" name="name" required>
Email : <input type="text" id="name" name="name" required>
Mobile : <input type="text" id="mobile" name="mobile" required>
Gender : <input type="text" id="gender" name="gender" >/*optional*/
Occupation : <input type="text" id="occupation" name="occupation" >/*optional*/
City : <input type="text" id="city" name="city" required>
Avatar : <input type="file" id="avatar" name="avatar" required>
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" />
===========
Edited
what I have tried for submit disable untill all field completed as follows :
First Thing :
<input type="submit" class="link-button-blue" id="register" value="PROCEED TO NEXT STEP" disabled="disabled" />
script :
<script>
$(document).ready(function (){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
$('#registration_form input[required]').on('input propertychange paste change', function() {
var empty = $('#registration_form').find('input[required]').filter(function() {
return this.value == '';
});
$('#register').prop('disabled', (empty.length));
});
https://jsfiddle.net/ot5kn5c7/
This should work.
Anytime anything changes on any required input check for the count of required fields that are not empty. Once there are 0 required empty inputs update the disabled property for the button. (0 evaluates as false)
If you didn't to disable the button and wanted to only stop the form from submitting you would attach to the submit event on the form and just prevent the default action using similar logic checking the length.
$('form').on('submit', function(e) {
var empty = $(this).find('input[required]').filter(function() {
return this.value == '';
});
if (empty.length) {
e.preventDefault();
alert('enter all required field!')
}
});
Working solution for your case: https://jsfiddle.net/j9r5ejho/
$('form').submit(function(){
var valid = true;
$('input[required]').each(function(i, el){
if(valid && $(el).val()=='' ) valid = false;
})
return valid;
})
Untested but it should work with something like this:
(function() {
// whenever you type in a field
$('form > input').keyup(function() {
var empty = false;
// scan all fields in this form with the attribute required
$('form').find('input[required]').each(function() {
// if it's empty, cancel the loop
if ($(this).val() == '') {
empty = true;
return false;
}
});
// in case we have an empty required field,
// disable submit button
if (empty) {
$('input:submit').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})();
In order to prevent posting the form on a button or input type="submit", you can simply use e.preventDefault() which would prevent from proceeding with the default behavior.If you are using jquery validation and have a required attribute, you can just invoke $.validate() to validate the form.
$('input:submit').click(function(e)
{
if(!$.validate())
e.preventDefault();
});
example : https://jsfiddle.net/DinoMyte/suj951ga/1/
Just in case you want to try something like this. This won't disable the submit button but if you want to stop it from submitting until all required fields are fill in. This should work.
Not sure what database your using but this is for the PDO. You can just change the connection part to mysqli.
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white
space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";}
}
if (empty($_POST["email"])) {
$emailErr = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>
I see so many people ask to disable a button when a textbox is empty . how about disable a button when a textbox has data ?
this is my button code
<input type="submit" name="submit" value="Reserve" />
this is my textbox code
Name : <br><br><input type="text" name="name" value="<?php echo $name;?>" <?php if($name != "") echo "readonly"?> /> <br><br>
Name : <br><br><input type="text" name="name2" value="<?php echo $name2;?>" <?php if($name2 != "") echo "readonly"?> /> <br><br>
<input type="submit" name="submit" value="Reserve" <?php echo ($name != "")?"disabled":""; ?>/>
Using jQuery
$(":input").bind('keyup mouseup',function(){
disable_button();
});
function disable_button()
{
flag = false;
$(":input").each(function(){
if($(this).val()==""){
flag=true;
}
});
if(flag){
$("input[type=submit]").prop("disabled",false);
}
else
{
$("input[type=submit]").prop("disabled",true);
}
}
Demo
Problem
I will try to include as much information as possible without complicating things, but i have a problem where when i submit a form the page refreshes thus closing the tab with the form on. The user then needs to click on the tab again to view the feedback.
Background info.
I have one webpage using JavaScript to open and close "tabs" (divs), on one of these tabs i have a form which POST's the user inputted data to a php script which then sends the data to an email address and then redirects back the the original page. However when the script redirects back to the page the tab is closed thus making the user re-click on the tab to open it again to see the automated feedback from the script.
What i have checked
I have checked and it is not the redirect causing the refreshing as it still happens when the form POST's to itself.
The website in question
Does anyone have any ideas?
Here is the HTML for the form, which is in the enquiry 'tab'.
<div class='content one'>
<div id="contact-form" class="clearfix">
<P>Quick And Easy!</P>
<br/>
<P>Fill out our super swanky contact form below to get in touch with us! Please provide as much information as possible for us to help you with your enquiry.</P>
<br/>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'invisible' : ''; ?>">Now sit back and relax while we go to work on your behalf, we'll keep you updated with information on our results and if you have any questions then we welcome your calls or emails on 078675675446 or isaaclayne#southwestcarfinder.co.uk</p>
<form method="POST" action="process.php">
<label for="enquiry">Make: </label>
<select id="make" name="make">
<option value="Ford" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Ford') ? "selected='selected'" : '' ?>>Ford</option>
<option value="BMW" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'BMW') ? "selected='selected'" : '' ?>>BMW</option>
<option value="Vauxhall" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Vauxhall') ? "selected='selected'" : '' ?>>Vauxhall</option>
</select>
<label for="Model">Model: <span class="required">*</span></label>
<input type="text" id="model" name="model" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['model'] : '' ?>" placeholder="Model of Car" required autofocus />
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="Budget">Your Budget: </label>
<select id="enquiry" name="enquiry">
<option value="300 or less" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'General') ? "selected='selected'" : '' ?>>£300 or less</option>
<option value="400 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Sales') ? "selected='selected'" : '' ?>>£400</option>
<option value="500 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Support') ? "selected='selected'" : '' ?>>£500 or more</option>
</select>
<label for="message">Additional Info: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
<span id="loading"></span>
<input type="submit" value="Find My Car!" id="submit-button" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery- 1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/plugins.js"></script>
<script src="js/script.js"></script>
<!--[if lt IE 7 ]>
<script src="js/libs/dd_belatedpng.js"></script>
<script> DD_belatedPNG.fix('img, .png_bg');</script>
<![endif]-->
</div>
PHP Script
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$make = $_POST['make'];
$model = $_POST['model'];
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//validate form data
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
//send email if all is ok
if($formok){
$headers = "From: Info#Columbus.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Telephone: </strong> {$telephone} </p>
<p><strong>Email Address: </strong> {$email} </p>
<br/>
<p><strong>Make: </strong> {$make} </p>
<p><strong>Model: </strong> {$model} </p>
<p><strong>Budget: </strong> {$enquiry} </p>
<br/>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
mail("dancundy#hotmail.com","New Enquiry",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'name' => $name,
'email' => $email,
'telephone' => $telephone,
'enquiry' => $enquiry,
'message' => $message
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
//header('location:' . $_SERVER['HTTP_REFERER']);
header('Location: index.php#contact-form' );
}
}
?>
You are making a POST request when you submit the form. POST request by default travel through an HTTP request that the browser sends to the server, and therefore the browser needs to load the new data that causes the site to refresh.
If you want the browser to not refresh then you need to do an AJAX request using Javascript on the client side. You can use jQuery to accomplish this.
try this
$('form').submit(function(e)
{
e.preventDefault();
})
Thank you #saman and #gpopoteur,
Your answers are great and do work, just wasn't working on my testing server.
This is what got to work in the end.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><script>
$('#form1').submit(function(e)
{
event.preventDefault();
$.ajax({
type : 'POST',
url : 'process.php',
data : $(this).serialize(),
success : function(response) {
}
});
});
What i did find is though that nothing is returned from the script. E.I any validation info or returned data? Not too much of a problem and i'll create a work around. Thank again