Multipe action="" attribute urls - javascript

I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?
HTML:
<form action="<?php echo htmlspecialchars($_server['php_self']);?>
, mailto:example#gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
<input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
</span><br/>
<label for="last">Last Name:</label>
<input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
</span><br/>
<label for="mail">Email:</label>
<input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
$emailErr;?>
</span><br/>
<label for="yearLevel">Year Level:</label>
<select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
<option>Year 8</option>
<option>Year 9</option>
<option>Year 10</option>
<option>Year 11</option>
<option>Year 12</option>
<option>Uni Student</option>
<option>Other</option>
</select>
<label for"comment">Comment:</label>
<textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
</textarea><br/><br/>
<input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
PHP:
<?php
//feedback form validation code
//start
//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";
//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "* Your first name is required!";
} else {
$firstName = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
$fnameErr = "* Only letters and white space allowed!";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "* Your last name is required!";
} else {
$lastName = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
$lnameErr = "* Only letters and white space allowed!";
}
}
if(empty($_POST["comment"])) {
$comment = "* the comment box is required!";
} else {
$comment = test_input($_post["comment"]);
}
if (empty($_POST["email"])) {
$emailErr = "* Your email is required!";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid Email Format!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//end
?>
JS script for a confirm when the user clicks submit. so it makes sense to the form.
<script type="text/javascript">
//confrim before submitting.
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
return true;
} else {
console.log("edit!");
return false;
}
}
</script>

You couldn't add multiple actions in the form action, You should send the form to a PHP file and then after validating, send the email by PHP mail function or other libraries like PHPmailer etc.

Simple answer: No, you cannot add multiple actions for tag, how you would the distinguish between which one to choose?
If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.
In your case, use mail PHP function to send mail from PHP script when you pass your validation.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">
and then in PHP
mail('somebody#example.com', 'Subject', 'Body', optionalHeaders);

You can't do it, but you can call mailto inside your ask() like,
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
// add mailto here
myWindow=window.open("mailto:example#gmail.com");
myWindow.close();
return true;
} else {
console.log("edit!");
return false;
}
}
And change form action like,
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
....
</form>

Related

Hide "submit" button once a form is sent successfully, then show success message

At the moment I have a working contact form. I'd like to hide the "submit" button of my form when the form is sent successfully and then display a success message.
At the moment it redirects, which I've left for the purpose of this request.
I've tried multiple solutions, tweaking of the js but js sure isn't my strong point. I've left the CSS in also for the purpose of this question as I believe that will be the route I need to go down.
<< ? php
if (empty($_POST) === false) {
session_start();
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$errors = array();
if (isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$fields = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
);
foreach($fields as $field => $data) {
if (empty($data)) {
//$errors[] = "The " . $field . " is required";
$errors[] = "Please fill-in the form correctly";
break 1;
}
}
if (empty($errors) === true) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid e-mail address";
}
}
if (empty($errors) === true) {
$name = test_input($_POST['name']);
$email = test_input($_POST['email']);
$message = test_input($_POST['message']);
$to = "example#example.com";
$subject = "example | You have a new message from ".$name;
$body = ......
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
$data = $_POST['name'].
' == Email: '.$_POST['email'].
' Message: '.$_POST['message'].
"\r\n";
$ret = file_put_contents('entries.log', $data, FILE_APPEND | LOCK_EX);
if ($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
header('location: ../sendmail/redirect.html');
}
$headers = "MIME-Version: 1.0".
"\r
#thank-you-message {
display: none;
}
#thank-you-message.show {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea>
<button type="submit">Send</button>
</form>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
You can use JavaScript to hide this button or generate this site by using PHP.
You have two possibilities, cookies or sessions.
Check if cookie or session is set, if not display the button or form, if is set hide button or form.
This can be done within a If/Else condition and a simple „print“ function.
Like (PHP)
IF (isset xxx = true) {
// print nothing
// redirect to page xxx.html
// or print Text like Lorem Ipsum
}
else {
print '<form method=“POST“ action=“form.php“> … </form>';
}
After submit the form you have to set a session or cookie in „form.php“.
When a user come back to this site, the site will check the cookie or session and print the form or not.
You have to change the IF/Else condition to your needs.
You can also print a „Thank you page“ or something else you want, you can also redirect to a other page by the header function within php.
Quick fix, you could try structuring your code in this format if using PHP
function save() {
$('.btn-danger').hide()
var number_i = $('#number_i').text();
var date_s = $('#date_s').text();
var name_p = "<?php echo $_POST['product_name']; ?>";
if (number_i != '___') {
$.post('saveEntry.php', {number: number_i, date: date_s, name: name_p}, function() {
$('#confirmation').text('Info: the data was saved!');
$('#confirmation').attr('class', 'alert alert-success');
})
} else {
alert('Introdu Numar Bon Fiscal!');
}
};
No need for JS for this. Assuming your form is parsing properly, you can add the following styles to your stylesheet.
#thank-you-message {
display: none;
}
button:focus ~ #thank-you-message {
display: block;
}
I removed your PHP and the rest of your form so that you can see a demonstration. See below:
Edit ~ added sample JS for the button to change text upon form submission. (Doesn't affect p displaying on button click)
function form_success() {
document.getElementById("myform").submit();
document.getElementById("btn").innerHTML = "Sent!";
}
#thank-you-message {
display: none;
}
button:focus {
background-color: green;
color: white;
}
button:focus~#thank-you-message {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);" id="myform">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea><br>
<button type="submit" id="btn" onclick="form_success()">Send</button>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
</form>

PHP email validation not working properly

I'm using radio buttons to display my form's textbox. I added a PHP script to validate the email and on completion, open another page. But nothing seems to be working. It shows the error message for when the textbox is empty, even when the submit button hasn't been pressed, and it refreshes the page if the email format isn't correct.
Here's my code:
<?php
// define variables and set to empty values
$emailErr = "";
$email = "";
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
else{
header("Location:create.php")
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
function ShowHideDiv() {
var chkYes1 = document.getElementById("chkYes1");
var dvtext1 = document.getElementById("dvtext1");
var chkYes2 = document.getElementById("chkYes2");
var dvtext2 = document.getElementById("dvtext2");
var button = document.getElementById("button");
dvtext1.style.display = chkYes1.checked || chkYes2.checked ? "block" : "none";
dvtext2.style.display = chkYes2.checked ? "block" : "none";
btn1.style.display = chkYes1.checked ? "block" : "none";
btn2.style.display = chkYes2.checked ? "block" : "none";
}
<div class="content login-container">
<div class="form-login">
<label for="chkYes1">
<input type="radio" id="chkYes1" name="chk" onclick="ShowHideDiv()" />
I am new on Swadonline
</label>
<br>
<br>
<div id="dvtext1" style="display: none" class="lgntxt">
Please enter your Email Address *
<br>
<input type="text" id="txtBox" name="email" />
</div>
<button style="display: none" id="btn1" class="btn third" type="submit" name="submit" value="Submit">CONTINUE</button>
</div>
</div>
In html change this line
<button style="display: none" id="btn1" class="btn third" type="submit" name="submit" value="Submit">CONTINUE</button>
to
<input type="submit" style="display: none" id="btn1" class="btn third" name="my_form_submit" value="CONTINUE">
Now in your php change as below:
<?php
// define variables and set to empty values
$emailErr = "";
$email = "";
if(isset($_POST['my_form_submit'])){ // only check validation if form has been submitted, else don't validate
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
else{
header("Location:create.php");
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
I've taken this route for form submissions once upon a time, since then I would highly recommend setting up PHPMailer for any project.
For the email part: PHPMailer is relatively easy to set up and has never let me down.
For the Validation, all you have to do is add a 'required' attribute to the forms, to my knowledge, the browser will do the rest :)
Hope this in any way helps!

Submitting form data with php with no page reload?

I have a contact form, on my personal portfolio webpage, made with PHP with a friends help (i'm a dummy when it comes to PHP.)
Although i have a problem with it. Whenever the submit button is pressed, and the mail is sent, it makes the page reload. How can i fix this?
I've copied (and changed the personal stuff) all my form, since i have no idea where or what to change:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subject = "";
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid e-mail format"; }
}
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = input($_POST["subject"]);
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = input($_POST["comment"]);
}
}
// MailGun cURL API //
$curl_post_data=array(
'from' => "$name <$email>",
'to' => 'my#mail.com',
'subject' => $subject,
'text' => $comment,
);
$service_url = 'mailgunlink.com';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:key-123456789123456789abc");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
// trim //
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<section id="kontaktformular">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row" id="kontakt">
<div class="six columns">
<label>Full Name <span class="error">*<?php echo $nameErr;?></span></label>
<input class="u-full-width" type="text" placeholder="Peter" name="name" id="navn">
</div>
<div class="six columns">
<label>Your Email <span class="error">*<?php echo $emailErr;?></span></label>
<input class="u-full-width" type="email" placeholder="Peter#Example.com" name="email" id="email">
</div>
<label>Subject <span class="error">*<?php echo $subjectErr;?></span></label>
<input class="u-full-width" type="text" placeholder="Design" name="subject" id="subject">
<label>Message <span class="error">*<?php echo $commentErr;?></span></label>
<textarea class="u-full-width" placeholder="Whatever..." name="comment" id="besked"></textarea>
</label>
<input class="button-primary change" type="submit" value="Send">
</div>
</form>
</section>
I hope the snippet is sufficient, even though it looks messy like this.
If you need more information feel free to yell at me for it.
Also, bonus question. I need the submit button to also HIDE the form (display: none; -> #kontaktformular) and SHOW another div (display: block; -> #feedbackmsg)
Thanks in advance! The first question is the most important!
I'm pretty sure that this question has already been asked and answered multiples. Either way to do it you'll have to use AJAX which is pretty simple and one way to do it is.
<section id="kontaktformular">
<form id="kontaktform" method="post">
<div class="row" id="kontakt">
<div class="six columns">
<label>Full Name <span class="error">*</span></label>
<input class="u-full-width" type="text" placeholder="Peter" name="name" id="navn">
</div>
<div class="six columns">
<label>Your Email <span class="error">*</span></label>
</div>
<label>Subject <span class="error">*</span></label>
<input class="u-full-width" type="text" placeholder="Design" name="subject" id="subject">
<label>Message <span class="error">*</span></label>
<textarea class="u-full-width" placeholder="Whatever..." name="comment" id="besked"></textarea>
</label>
<input id="kontaktform_input" class="button-primary change" type="submit" value="Send">
</div>
</form>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$("#kontaktform").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
$.ajax({
type: "POST",
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
}
});
});
</script>
Yes AJAX is the answer you are looking for in this case:
Add an ID to the submit button eg.
<input class="button-primary change" id="Kontakt_Submit" type="submit" value="Send">
Then next in your js file write a similar code
jQuery("#Kontakt_Submit").click(function () {
//serialize the data, in simple terms for you to understand, it will
// get all the input element name value, then this data will be sent as POST DATA
var data = jQuery('form').serialize();
console.log('data-->' + data);
$.ajax({
type: 'POST',
dataType: "json",
url: 'ajax.php',
data: {
check: 'Kontakt_Form',
Kontakt_Form_Data: data
},
success: function (data) {
}
});
});
Next in your ajax.php file add this code
if ($_POST['check'] == 'Kontakt_Form') {
$result_array = array();
$extracted_Array= array(); // since we declared both the variable names as "value" in JQuery
parse_str($_POST['Kontakt_Form_Data'], $extracted_Array);
$name= $extracted_Array['name'];
$email= $extracted_Array['email'];
...//do the the other things what you need to do here, then enter in result array and return it for your output values if any.
}
Hope this will help you understand in a simple way to set up what you wanted.

HTML: Get value from text fields and email them

I am using bootstrap to create input fields. When someone clicks the "Submit" button I want the values (if they are valid) to be emailed to myself. I am having trouble even making sure they are valid. Below is my code
<form action="tryjs_submitpage.htm" onsubmit="return myFunction()">
<fieldset class="form-group">
<label for="name">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name">
</fieldset>
<fieldset class="form-group">
<label for="email">Email Address*:</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
</fieldset>
<fieldset class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" id="company" placeholder="Company Name">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function myFunction() {
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
submitOK = "true";
if (name.length == 0) {
alert("You must enter your name");
submitOK = "false";
}
if (email == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (message.length == 0) {
alert("You must enter a message");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
I modified the script from here, but when I click submit it says tryjs_submitpage.htm doesn't exist. Obviously this is an issue, but I can't seem to find tryjs_submitpage.htm anywhere to get it to work. Further I wanted to know if there was a way to trigger an email send with the appropriate information to my personal email. Thanks for the help!
You can't send an email directly with javascript for security reasons.
Suppose there is a feature in JavaScript to send email. Some malicious coder can write a script to send email to some address immediately when you visit their page. This will reveal your email address to some third party without your knowledge. They will start filling your mail box with lots of spam messages! However, there are alternatives as explained below. link
You can however open the user's mail client, to do so:
<form action="" onsubmit="sendMail(); return false">
...
...
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function sendMail() {
var link = "mailto:me#abc.com"
+ "?cc=myCCaddress#example.com"
+ "&subject=" + escape("This is my subject")
+ "&body=" + escape(document.getElementById('myText').value)
;
window.location.href = link;
}
</script>
You can't send a mail directly from the browser, however you can use third party technologies like http://www.emailjs.com/ or create a .php file using php native mail function to send mail.
Below is the HTML, JS(Jquery AJAX) and PHP file that handles mail sending.
In this case the PHP script handles email verification, but you can also use HTML require or JS regex to check at the client side before sending a POST request to the server
HTML
<form method="POST" action="" id="contactform">
<p>
<label for="name">Your Name</label>
<input type="text" name="name" class="input" >
</p>
<p>
<label for="email">Your Email</label>
<input type="text" name="email" class="input">
</p>
<p>
<label for="message">Your Message</label>
<textarea name="message" cols="88" rows="6" class="textarea" ></textarea>
</p>
<input type="submit" name="submit" value="Send your message" class="button transition">
</form>
JS (JQuery)
var $contactform = $('#contactform'),
$success = 'Your message has been sent. Thank you!',
$url = 'link to the hosted php script';
$contactform.submit(function(e) {
$.ajax({
type: 'POST',
url: $url,
data: $(this).serialize(),
dataType: "json",
xhrFields: {
withCredentials: true
}
})
.done(function(msg) {
console.log(msg)
if (msg.success == true) {
response = '<div class="success">' + $success + '</div>';
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Hide any previous response text.
$('.error, .success').remove();
// Show response message.
$contactform.prepend(response);
})
.fail(function(msg) {
console.log(msg)
});
e.preventDefault();
});
PHP
<?php
// Array to hold validation errors and response data.
$errors = array();
$data = array();
// Validate the variables
// if any of these variables don't exist, add an error to our $errors array
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: *');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'POST') {
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
}
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "admin#example.com";
$subject = "Website Contact Form: ".$name;
$headers = "From: noreply#example.com\n"; // email address the generated message will be from. Recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: ".$email;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
My advice is don't do the form validation yourself, just let the browser do it. You will need to change the input type on your email input to email, and you will need to add the required attribute to every one you want to be required.
This way instead of using JavaScript you can just use standards-compliant HTML.
Then, since you can't send email directly from the browser, you need a third-party service to send the email, like for example Formspree. Alternatively you could write a server-side script for sending email, but it's much easier to just use a service.
Here is the final code:
<form action="https://formspree.io/your.email.here#example.com">
<fieldset class="form-group">
<label for="usr">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name" name="message" required="required">
</fieldset>
<fieldset class="form-group">
<label for="exampleInputEmail1">Email Address*:</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email" required="required">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message" name="message" required="required"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
If you want to use Formspree and also have your visitors enter their company name, you can hack it by giving the company name field a name of "subject", which Formspree will forward to your email alongside the rest of the fields.
You have a little mistake in your code,
parameter document.getElementById is element id :
change code :
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
TO this :
var name = document.getElementById("usr").value;
var email = document.getElementById("exampleInputEmail1").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;

How to disable submit till only required fields are filled up

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>

Categories