I'm working in a website that needs to have the same form displayed multiple times on the same page.
The plugin that builds the forms is Gravity Forms.
I have already research on the documentation provided and I couldn't find any action that does the job.
I think I'll need to create a function that store in an array the ID of every single form created and do a comparison for every new form, so then I can probably change the ID of the form element(???).
Any guesses?
Solved the problem by printing the GravityForm inside a noscript tag and removing from that when the form is required.
See the example:
var $formContainer = $(".formContainer");
function hide_form($container) {
$container.slideUp();
var add_noscript_tag = "<noscript>" + $container[0].innerHTML + "</noscript>";
$container.empty();
$container.append(add_noscript_tag);
}
function show_form($container) {
var remove_noscript_tag = $container[0].innerHTML
.replace("<noscript>", "")
.replace("</noscript>", "");
$container.empty();
$container.append(remove_noscript_tag);
$container.slideDown();
}
$("button").click(function() {
var $FormContainer = $(this).next();
if ($FormContainer.is(":visible")) {
hide_form($FormContainer);
} else {
var $otherForm = $(".formContainer:visible");
if ($otherForm.length > 0) {
hide_form($otherForm);
}
show_form($FormContainer);
}
});
button {
margin: 20px 0;
}
.formContainer {
display: none;
background: #eee;
}
.formContainer form {
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button>open form 1</button>
<div class="formContainer">
<noscript>
<form>
<input type="text" value="Name"/>
<input type="text" value="Phone"/>
<input type="text" value="Email"/>
</form>
</noscript>
</div>
</div>
<div>
<button>open form 2</button>
<div class="formContainer">
<noscript>
<form>
<input type="text" value="Name"/>
<input type="text" value="Phone"/>
<input type="text" value="Email"/>
</form>
</noscript>
</div>
</div>
Related
So I am creating a website that tracks a user's Shooting Score for Rifle Competitions. I have a Create Match tab, which brings them to a page containing a
Weapon Selection drop down, then a Date input, then a Location input, and then I have a Save Match button which will send these three inputs to a database along with a uniqueID (primary key, auto incremented) which will allow them to distinguish which match is which.
Now for each match you can create a String of Fire which the user can select. So on the same page, I have when the user presses Save Match, it sends the data, and then brings up another Dropdown box which houses the 4 String of Fire modes (200 yd slow, 200yd rapid, 300yd rapid, 600yd slow). And then a Create String button next to that which will bring down 10 target scores they can fill in after they push the button. the problem I am having is that when this button is pushed, it deletes the Create String dropdown box and button as well, and I'm not entirely sure what's wrong. I think it has something to do with how I'm using POST and that I am just creating a dropdown + button when they push Save Match....
Sorry for the long block of text, I'll try to break it down more if that was too confusing.
So basically I want to be able to push the first button (And retain w/e the user put in which I have working), and then it brings up a dropdown with 4 entries and a button, and then when that second button is created, a table of 10 entries is brought up, with a Save button, and when THAT button is pushed, it sends the 10 entries to the database. I can get the database transfer stuff working, I just need the creating more functional buttons/text inputs to work first.
Thank you for your time!
Code for HTML
<form name="table" action ='' method="post">
Rifle:
<select name="wpn" id="wpn">
<option>AR15</option>
<option>HK416</option>
<option>M1 Garand</option>
<option>M14</option>
<option>M4/M16</option>
<option>M24</option>
<option>SSG500</option>
<option>SSG556</option>
</select>
Date: <input type="date" name = "date" id="date" value = "<?php echo $_POST['date']; ? >">
Location:<input type="text" name="loc" id="loc" value = "<?php echo $_POST['loc']; ?>" />
<button type="submit" name = "save" value="Save Match">Save Match</button>
Code for PHP
<?php
//if ($_SERVER['REQUEST_METHOD'] == "POST"){
if($_POST['save'] == 'Save Match'){
if($_POST["date"]==NULL){
apologize("Please enter a valid date!");
}
else if($_POST["loc"]==NULL){
apologize("Please enter a location!");
}
$id = $_SESSION['id'];
$wpn = $_POST['wpn'];
$date = $_POST['date'];
$loc =$_POST['loc'];
//if(isset($_POST['button'])){
if(query("INSERT INTO matches (id, weapon, date, location)
VALUES (?, ?, ?, ?)",
$id, $wpn, $date, $loc) === false){
apologize("Sorry insertion of data failure!!!");
}else{
// redirect("../public/matches.php");
//header("Location: ../public/matches.php");
?>
<br /><br />
Strings of Fire:
<select name="mode" id="mode">
<option>200 Yard Slow</option>
<option>200 Yard Rapid</option>
<option>300 Yard Rapid</option>
<option>600 Yard Slow</option>
</select>
<button type="submit" name="save" value="Create String">Create String</button>
<?php
if(($_POST['save']) == 'Create String'){
echo test;
}
}
}
?>
</form>
Okay, this is a work-in-progress, but here goes.
I split what you've shown into two separate files; here's the UI page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Shooting Scores for Rifle Competitions</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<style>
body {
background: #e8e8e8;
}
.step {
width: 50%;
margin: 1em auto;
padding: 1em;
background: #fff;
}
#step1 select.weapon,
#step2 select.fire-string
{
width: 50%;
}
#step1 input.date
{
width: 10em;
}
#step3 ol.scores-list li
{
margin-bottom: 1em;
}
#step3 input.score
{
width: 8em;
}
</style>
</head>
<body>
<div class="container">
<?php
require('process.php');
?>
<div id="step1" class="step">
<form class="table" action="" method="post" id="step1-form" role="form">
<div class="form-group">
<label>Rifle:</label>
<select name="wpn" id="wpn" class="form-control weapon">
<option>AR15</option>
<option>HK416</option>
<option>M1 Garand</option>
<option>M14</option>
<option>M4/M16</option>
<option>M24</option>
<option>SSG500</option>
<option>SSG556</option>
</select>
</div>
<div class="form-group">
<label>Date:</label>
<input type="date" name="date" id="date" value="<?php echo $_POST['date']; ?>" class="form-control date" />
</div>
<div class="form-group">
<label>Location:</label>
<input type="text" name="loc" id="loc" value="<?php echo $_POST['loc']; ?>" class="form-control" />
</div>
<button type="submit" name="save-match" id="save-match" value="step1" class="btn btn-default">Save Match</button>
</form>
</div>
<div id="step2" class="step hide">
<form class="table" action="" method="post" id="step2-form" role="form">
<div class="form-group">
<label>Strings of Fire:</label>
<select name="mode" id="mode" class="form-control fire-string">
<option>200 Yard Slow</option>
<option>200 Yard Rapid</option>
<option>300 Yard Rapid</option>
<option>600 Yard Slow</option>
</select>
</div>
<button type="submit" name="save-string" id="save-string" value="step2" class="btn btn-default">Create String</button>
</form>
</div>
<div id="step3" class="step hide">
<form class="table" action="" method="post" id="step3-form" role="form">
<div class="form-group">
<label>Target Scores:</label>
<ol class="scores-list">
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
</ol>
</div>
<button type="submit" name="save-scores" id="save-scores" value="step3" class="btn btn-primary">Save Scores and Finish!</button>
</form>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(function () {
// http://api.jquery.com/on/
$(document)
.on('click', '#save-match', function (e) {
e.preventDefault();
var button = $(this);
// http://api.jquery.com/serialize/
var form = $('#step1-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
// http://api.jquery.com/jquery.post/
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
// http://api.jquery.com/slidetoggle/
$('#step1').slideToggle('slow', function () {
// http://api.jquery.com/removeclass/
$('#step2').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-string', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step2-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
$('#step2').slideToggle('slow', function () {
$('#step3').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-scores', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step3-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
alert(result);
})
.fail(function () {
});
});
});
</script>
</body>
</html>
Here's the server script:
<?php
if(isset($_POST['save-match']))
{
$is_valid = true;
# step 1
if(empty($_POST["date"]))
{
$is_valid = false;
apologize("Please enter a valid date!");
}
if(empty($_POST["loc"]))
{
$is_valid = false;
apologize("Please enter a location!");
}
if($is_valid)
{
$id = $_SESSION['id'];
$wpn = $_POST['wpn'];
$date = $_POST['date'];
$loc =$_POST['loc'];
if(!query("INSERT INTO matches (id, weapon, date, location) VALUES (?, ?, ?, ?)", $id, $wpn, $date, $loc))
{
apologize("Sorry insertion of match data failure!!!");
}
else
{
# step 1 finished successfully.
}
}
}
else if(isset($_POST['save-string']))
{
# step 2
if(empty($_POST["mode"]))
{
apologize("Please enter a valid mode!");
}
else
{
$id = $_SESSION['id'];
$mode =$_POST['mode'];
if(!query("YOUR QUERY HERE TO INSERT / UPDATE MODE", $id, $mode))
{
apologize("Sorry insertion of mode data failure!!!");
}
else
{
# step 2 finished successfully.
}
}
}
else if(isset($_POST['save-scores']))
{
echo "Received " . count($_POST['scores']) . " scores!";
# step 3
if(empty($_POST["scores"]))
{
apologize("Please enter your scores!");
}
else
{
$id = $_SESSION['id'];
$scores = $_POST["scores"]; # this will be an array
if(!query("YOUR QUERY HERE TO INSERT / UPDATE SCORES", $id, $scores))
{
apologize("Sorry insertion of scores data failure!!!");
}
else
{
# step 3 finished successfully.
}
}
}
else
{
# assuming a GET request at this point
}
?>
I obviously have no idea what your apologize() or query() functions are. For sake of the example I'm choosing to assume apologize() simply echos a string, or perhaps throws an exception. The important bit is the script section at the end of the UI page:
$(function () {
// http://api.jquery.com/on/
$(document)
.on('click', '#save-match', function (e) {
e.preventDefault();
var button = $(this);
// http://api.jquery.com/serialize/
var form = $('#step1-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
// http://api.jquery.com/jquery.post/
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
// http://api.jquery.com/slideToggle/
$('#step1').slideToggle('slow', function () {
// http://api.jquery.com/removeclass/
$('#step2').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-string', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step2-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
$('#step2').slideToggle('slow', function () {
$('#step3').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-scores', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step3-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
alert(result);
})
.fail(function () {
});
});
});
I've included links to each jQuery function where it's first used, so I'd recommend reading the manual for each one at some point. Here's what happens:
To begin, we bind "event listeners" for each of the submit buttons, using .on(). By hanging the listeners off of document, we can make sure the listeners still work even if the forms or buttons get replaced at some point. When using .on(), the first argument is the specific event we want to handle (in this case, the click event). The second argument defines a filter; basically, only handle a click event if an element matching that selector was the trigger. The last argument is a function to call when event needs to be handled.
Next, we get a reference to the button that triggered the event (which we'll use in a second). We then call jQuery's .serialize() on the relevant form for this button, which generates a form-encoded string we can use to post the form asynchronously (more on that in a minute). Unfortunately for our PHP script, the serialize function does not include the button in the string (for reasons beyond the scope of this question), so we have to manually append the relevant values to the string.
Continuing on, we use jQuery's $.post() function to send our serialized data to the server, where it will be processed as if it were a normal POST. $.post() has a few functions that we can use to handle the result of the POST; the two I mostly use are .done() and .fail(). .done() will be called if the request was successful (meaning it returned a 3xx HTTP code) and .fail() is called for 4xx or 5xx HTTP codes.
Finally, when receiving a successful response, we hide the current step and show the next, until we get to the last step. From there I would assume you either return to the initial view, or show some sort of success message...
I basically repeat the same logic for the three "steps" you've outlined. What this particular script does is hide and show each step as your user walks through it. It's obviously incomplete, so let me know where to elaborate.
NOTE: I've included links to CDN versions of both jQuery and Bootstrap (just to make the UI look a little less plain and take advantage of some helper classes).
Searching event isn't triggered with enter key but works fine if manually press Search button.
Here's my simple script
$('#searchproductbrand').live('click',function() {
var search = $('.searchproductbrand').val();
window.open('search.php?search='+search,'_self');
});
$('.searchproductbrand').keypress(function(e) {
if (e.which == 13) {
var search = $('.searchproductbrand').val();
window.open('search.php?search='+search,'_self');
}
});
And here is my textbox & button.
<input type="search" id="text" class="searchproductbrand" placeholder="Search for Product, Brand" onkeyup="showResult(this.value)" autofocus="autofocus" />
<input type="button" id="searchproductbrand" class="button" value="Search" style="padding: 10px 10px;"/>
So pressing button works fine but pressing enter key while searching doesn't work. Anyone can help?
Have you tried live("keypress") ?
$('.searchproductbrnad') is it brand or brnad? typo?
pressing enter submits a form, so just make it a proper form...
<script>
function myFunction(){
//do stuff
return false;
}
</script>
<form onsubmit="return myFunction();">
<input type="search" id="text" class="searchproductbrand" placeholder="Search for Product, Brand" onkeyup="showResult(this.value)" autofocus="autofocus" />
<input type="submit" id="searchproductbrand" class="button" value="Search" style="padding: 10px 10px;"/>
</form>
You have to create the document object.
Change your keypress code like this
$(document).keypress(function(e) {
if (e.which == 13) {
var search = $('.searchproductbrand').val();
window.open('search.php?search='+search,'_self');
}
});
I hope, it will solve your issue.
I currently have a form that is posting a file, however I want to interrupt the submit so I can display a 'loading' gif and then submit. That way the gif acts as a loading symbol for larger files. I need a way to change the css class attribute from display:none to display:all. Any help?
My code:
<html>
<head>
<title>Upload your media!</title>
<style type="text/css">
load {
display: none;
}
</style>
<script>
function validateForm()
{
var x=document.forms["mediaupload"]["title"].value;
if (x==null || x=="")
{
alert("Title must be filled out");
return false;
}
var y=document.forms["mediaupload"]["info"].value;
if (y==null || y=="")
{
alert("Description must be filled out");
return false;
}
var z=document.forms["mediaupload"]["file"].value;
if (z==null || z=="")
{
alert("You need to select a file to upload");
return false;
}
}
</script>
</head>
<body>
<h1>TOOB</h1>
<form name="mediaupload" action="upload_file.php" onsubmit="return validateForm()" method="post"
enctype="multipart/form-data">
<fieldset>
<legend><h4>Upload</h4></legend>
Title:<input type="text" name="title"><br>
Description:<textarea rows="10" cols="30" name="info">Write your desiption here</textarea><br>
Anonymous:<input type="checkbox" name="anonymous"><br>
File Upload:<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</form>
<load><img id="loading" src="sitemedia/loading.gif" ></load>
</body>
</html>
use jQuery for this, remove the default submit and add timeout
$('form').submit(function(e)) {
e.preventDefault();
setTimeout(function() {
this.submit();
}, 5000); // in milliseconds
}
$("#form_id").submit(function(e){
e.preventDefault();
//Code for displaying the image
});
I was able to do this in pure javascript.
HTML
I changed the submit button to this:
<input type="button" onclick="loadFunc()" name="submit" value="Submit">
And added this loading div:
<div id="loading" style="display:none">
<img src="sitemedia/loading.gif" />
</div>
JavaScript
function loadFunc() {
document.getElementById("loading").style.display = "block";
document.mediaupload.submit();
}
See CodePen here.
On clicking the button magic1 or magic2, the div mybox will be updated with a text, button id and button (different for magic1 and magic2).
After clicking on the newly generated button it should display the button id of the newly generated button in the box div. When I click on the newly generated button, box div is not getting updated. Here is the code.
jquerycode.php is the initial file. On clicking the button magic1 or magic2, Ajax will call the page session.php.
jquerycode.php file
<!doctype html>
<?php
$first=$_POST['q'];
echo $first;
?>
<html>
<head>
<meta charset="utf-8" />
<title>My jQuery Ajax test</title>
<style type="text/css">
#mybox {
width: 300px;
height: 250px;
border: 1px solid #999;
}
#box {
width: 300px;
height: 250px;
border: 1px solid #999;
position: absolute;
right:210px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".magic_button").click(function() {
var data = $(this).attr('id');
//alert (data);
$.ajax({
type: "POST",
url: "session.php",
data: { 'id': data }
}).done(function(msg) {
$("#mybox").html(msg);
});
});
});
</script>
<script>
$(".fir").click(function() {
var dataa = $(this).attr('id');
alert ("hello");
$.ajax({
type: "POST",
url: "jquerycode.php",
data: { 'q': dataa }
}).done(function(msg) {
$("#box").html(msg);
return false;
});
});
</script>
</head>
<body>
The following div will be updated after the call:<br />
<div id="mybox">
</div>
<div id="box">
</div>
<form name="magic">
<!-- <label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label> -->
<input type="button" class="magic_button" name="magic_button" id="magic_button_1" value="magic1" />
<input type="button" class="magic_button" name="magic_button" id="magic_button_2" value="magic2" />
</form>
</body>
</html>
session.php file
<?php
$id = $_POST['id'];
$id = ucwords(implode(' ',explode('_',$id)));
if($id==="Magic Button 2")
{
echo "hey its button 2!!";
?>
<input type="button" name="butb" id="second" class="fir" value="second"/>
<?php
}
else
{
echo "hey its button 1!!";
?>
<input type="button" name="buta" id="first" class="fir" value="First"/>
<?php
}
echo $id;
?>
Best if you can use JQuery Live() for dynamic Generated Elements :
$("a.offsite").live("click", function(){ alert("Goodbye!"); }); // jQuery 1.3+
Beca JQuery Live() is deprecated you need to use JQuery on()
$("#elementid").on("click", function(event){
alert($(this).text());
});
I asked this question before about trying to create a contact form which allows validation (displays an error when not filled in or filled in incorrectly) - https://stackoverflow.com/questions/16331369/creating-a-contact-form-which-displays-error-when-not-filled-in
The end functions don't have to work (meaning it doesn't have to send but it will still be nice for this to work 100%) because I'm creating a template of this but I do want the validation and message to come up if it's filled incorrectly. Please take a look and see what I did wrong, thanks in advance.
My HTML Code:
<div class="hr dotted clearfix"> </div>
<!-- Contact Form -->
<form action='index.html' method='post' id='contact_form'>
<h3>Contact Form</h3>
<div class="hr dotted clearfix"> </div>
<ul>
<li class="clearfix">
<label for="name">Name</label>
<input type='text' name='name' id='name' />
<div class="clear"></div>
<p id='name_error' class='error'>Insert a Name</p>
</li>
<li class="clearfix">
<label for="email">Email Address</label>
<input type='text' name='email' id='email' />
<div class="clear"></div>
<p id='email_error' class='error'>Enter a valid email address</p>
</li>
<li class="clearfix">
<label for="subject">Subject</label>
<input type='text' name='subject' id='subject' />
<div class="clear"></div>
<p id='subject_error' class='error'>Enter a message subject</p>
</li>
<li class="clearfix">
<label for="message">Message</label>
<textarea name='message' id='message' rows="30" cols="30"></textarea>
<div class="clear"></div>
<p id='message_error' class='error'>Enter a message</p>
</li>
<li class="clearfix">
<p id='mail_success' class='success'>Thank you. I'll get back to you as soon as possible.</p>
<p id='mail_fail' class='error'>Sorry, an error has occured. Please try again later.</p>
<div id="button">
<input type='submit' id='send_message' class="button" value='Submit' />
</div>
</li>
</ul>
</form>
</div>
And here's my code for the javascript:
$(document).ready(function(){
$('#send_message').click(function(e){
e.preventDefault();
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
}else{
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
if(error == false){
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
$.post("send_email.php", $("#contact_form").serialize(),function(result){
if(result == 'sent'){
$('#button').remove();
$('#mail_success').fadeIn(500);
}else{
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Submit');
}
});
}
});
});
And part of CSS:
p.error {margin-left:140px; margin-top:10px;}
#contact_form ul {float:left;}
#contact_form ul li {margin:10px 0; list-style:none; position:relative; clear:both;}
#contact_form label {line-height:35px; width:100px; text-align:right; float:left; margin-right:10px;}
#contact_form input#name,
#contact_form input#email,
#contact_form input#subject,
#contact_form textarea {float:left; padding:8px; border:1px solid #CCCCCC; margin-left:10px; background:#fcfcfc; -moz-border-radius:5px; -webkit-border-radius:5px;}
#contact_form input#name,
#contact_form input#email,
#contact_form input#subject {width:400px;}
#contact_form textarea {width:500px;height:150px; resize: none;}
#contact_form input.button {float:right;}
You have the variable error declared several times. In this jsbin you have you code rectified, it runs ok.
edit 1: Regarding your comment I've updated the code. Now the erros don't show at the beginning.
edit 2: "because I'm creating a template of this" — in that case I would recommend you make your code more abstract, or to use a library for form validation.
I did something like this on my website for validation :
rename the id's of the elements you want checked to "1", "2", "3" etc.
rename the id's of the error messages you want displayed to "1a", "2a", "3a" etc.
Then I did something like this :
function validate()
{
for(i = 1; i< totalelements; i++)
{
if(document.getElementById(i).length >= 0 )
{
$("#" + i + "a").fadeIn(500);
}
else
{
$("#" + i + "a").fadeOut(500);
}
}
}
Now the only thing you gotta do is assign the function somewhere (on a button, keyup/down etc)
Hope this helps.
you just try
input type='button' id='send_message' class="button" value='Submit' />
instead of
input type='submit' id='send_message' class="button" value='Submit' />
Use this jQuery validation plugin - http://docs.jquery.com/Plugins/validation
This is very strong validation plugin. It will just take you 10 seconds to apply this to your contact form. This is also my favourite one.
There is a keyword added in HTML5 for required fields:
<input type="text" name="username" required>
However, this won't be cross-browser so in such case the best approach could be a jquery plugin.