I have a simple "terms of use" checkbox set up and I want users to check it before submitting the form. I'm using the WordPress plugin "WP-Polls".
Here's what I've tried:
$('.wp-polls-form').submit(function() {
if ($('input:checkbox', this).is(':checked')) {
// everything is fine...
} else {
alert('Please agree to the Terms of Use.');
return false;
}
});
The HTML:
<form id="polls_form_1" class="wp-polls-form" action="/index.php" method="post">
<p style="display: none;"><input type="hidden" id="poll_1_nonce" name="wp-polls-nonce" value="12a6404147"></p>
<p style="display: none;"><input type="hidden" name="poll_id" value="1"></p>
<div id="polls-1-ans">
<ul>
<li><input type="radio" id="poll-answer-1" name="poll_1" value="1"></li>
<li><input type="radio" id="poll-answer-2" name="poll_1" value="2"></li>
<li><input type="radio" id="poll-answer-3" name="poll_1" value="3"></li>
</ul>
<label class="check-terms"><input type="checkbox">I am over 18 and I have read and understand the Terms of Use</label>
<input type="button" name="vote" value="Vote" class="Buttons" onclick="poll_vote(1);">
Edit 1:
Updated it to this to include radio buttons:
//Make sure checkbox and radio are checked before submitting
$('.wp-polls-form').submit(function() {
if ($('input:checkbox', this).is(':checked') &&
$('input:radio', this).is(':checked')) {
// everything is fine...
} else {
alert('Please agree to the Terms of Use.');
return false;
}
});
Edit: 2
Thanks to #AnthonyGarcia. The buttons work exactly how I'd like them to, but the only problem is that the form does not submit.
For the submit button, I changed the type from button to submit and also got rid of onclick="poll_vote(1);".
<input type="submit" name="vote" value="Vote" class="Buttons" />
$(function() {
window.poll_vote = function(num) {
console.log(num);
}
$('.wp-polls-form').submit(function(e) {
if (!$('input:radio', this).is(':checked')) {
alert('Please pick a beat.');
return false;
}
if (!$('input:checkbox', this).is(':checked')) {
alert('Please agree to the Terms of Use.');
return false;
}
poll_vote(1);
return false;
});
});
The live site can be seen here. The relevant section is the dark voting section on top.
Edit: 3
Here is the function for poll_vote(). I got it from the polls-js.dev.js file in the plugin here: https://github.com/lesterchan/wp-polls
// When User Vote For Poll
function poll_vote(current_poll_id) {
jQuery(document).ready(function($) {
if(!is_being_voted) {
set_is_being_voted(true);
poll_id = current_poll_id;
poll_answer_id = '';
poll_multiple_ans = 0;
poll_multiple_ans_count = 0;
if($('#poll_multiple_ans_' + poll_id).length) {
poll_multiple_ans = parseInt($('#poll_multiple_ans_' + poll_id).val());
}
$('#polls_form_' + poll_id + ' input:checkbox, #polls_form_' + poll_id + ' input:radio, #polls_form_' + poll_id + ' option').each(function(i){
if ($(this).is(':checked') || $(this).is(':selected')) {
if(poll_multiple_ans > 0) {
poll_answer_id = $(this).val() + ',' + poll_answer_id;
poll_multiple_ans_count++;
} else {
poll_answer_id = parseInt($(this).val());
}
}
});
if(poll_multiple_ans > 0) {
if(poll_multiple_ans_count > 0 && poll_multiple_ans_count <= poll_multiple_ans) {
poll_answer_id = poll_answer_id.substring(0, (poll_answer_id.length-1));
poll_process();
} else if(poll_multiple_ans_count == 0) {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
} else {
set_is_being_voted(false);
alert(pollsL10n.text_multiple + ' ' + poll_multiple_ans);
}
} else {
if(poll_answer_id > 0) {
poll_process();
} else {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
}
}
} else {
alert(pollsL10n.text_wait);
}
});
}
How about this? Hope it helps. Thanks
$('.wp-polls-form').submit(function() {
var isCheckboxChecked = $("input[type*='checkbox']").filter(":checked");
if (isCheckboxChecked) {
// everything is fine...
} else {
alert('Please agree to the Terms of Use.');
return false;
}
});
Your code is never called, because you are not submitting your form. You have to replace this:
<input type="button" name="vote" value="Vote" class="Buttons" onclick="poll_vote(1);">
By something like this:
<input type="submit" name="vote" value="Vote" class="Buttons">
Here is a fiddle with the modified code: http://jsfiddle.net/5st235fn/
I love to replace submit buttons with simple buttons and then submit forms programatically (or POSTing their values with ajax). However, your have an onclick="poll_vote(1);" that we don't know what's doing, so this answer will just make a guess.
If there's a poll_vote and you really mean to call it, try adding this to the end
function poll_vote(param) {
... current code ...
if ($('input:checkbox', '.check-terms').is(':checked')) {
$('.wp-polls-form').submit();
} else {
alert('Please agree to the Terms of Use.');
return false;
}
}
Related
I'm trying to validate my signup form using JavaScript. I submit the form and the default action is prevented but none of my error handler classes show up, nor do I get any errors in my error log. if anyone can show me what I'm doing wrong, it would greatly appreciated. I'm trying to show a red background on the input fields if the user doesn't fill in the input.
$(document).ready(function () {
$("#signupForm").submit(function (e) {
removeFeedback();
var errors = validateSignup();
if (errors == "") {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
});
function validateSignup() {
var errorFields = new Array();
//Check required fields to see if they have anything in them
if ($('#signupFirst').val() == "") {
errorFields.push('first');
}
if ($('#signupLast').val() == "") {
errorFields.push('last');
}
if ($('#signupEmail').val() == "") {
errorFields.push('email');
}
if ($('#signupPassword').val() == "") {
errorFields.push('pwd');
}
if (!($('#signupEmail').val().indexOf(".") > 2) && ($('#signupEmail').val().indexOf("#"))) {
errorFields.push('email');
}
return errorFields();
}
function provideFeedback(errorFields) {
for (var i = 0; i < errorFields.length; i++) {
$("#" + errorFields[i]).addClass("inputError");
$("#" + errorFields[i] + "Error").removeClass("errorFeedback");
}
}
function removeFeedBack() {
$('input').each(function () {
$(this).removeClass("inputError");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="index-bg-wrapper">
<div class="main-signup-container">
<form id="signupForm" class="signup-form" action='include/signup.inc.php' method='POST'>
<input id="signupFirst" type="text" name="first" placeholder="First Name">
<input id="signupLast" type="text" name="last" placeholder="Last Name">
<input id="signupEmail" type="text" name="email" placeholder="Email">
<input id="signupPassword" type="password" name="pwd" placeholder="Password">
<button type="submit" name="submit">Signup</button>
</form>
</div>
</div>
</body>
This is not ok:
return errorFields(); // Here you're trying to call a function with an array.
Just return the array: return errorFields;
Another problem is the comparison:
if (errors == "") { // This is not ok (it's always false), so, what you want to check is the length of errors.
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
So, check for the length:
if (errors.length === 0) {
return true;
} else {
provideFeedback(errors);
e.preventDefault();
return false
}
Here you go buddy, I have fixed multiple errors though very minor in your code but its working fine now.
Plnkr:
http://embed.plnkr.co/MaUzZh1zUFBL4y8qAf6n/
You were pushing wrong name inside the errorFields array.
Due to wrong field name and DOM id mismatch jquery couldn't find the element and apply the class.
I hope you can compare and get this code working.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need to made a simple contact form validaton. I´m newbie in Javascript. I tried many tutorials for newbies, hovever, no one tutorial solved my situation, so I´m trying to made my own JS.
But it have two issues:
Form is sent though is empty, although incorrect validation
If validation is failed, it should return all errors on same time
$("#submit").click(function () {
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
function validate() {
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
return false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
return false;
}
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
return false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
return false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
return false;
}
return (true);
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form autocomplete="off" id="contact-form" method="post" enctype="multipart/form-data" action="modules/process.php">
<div class="group">
<input type="text" class="move" name="f1" id="f1" /><span class="error" id="f1Err"></span>
<label>Name</label>
</div>
<div class="group">
<input type="text" class="move" name="f2" id="f2" /><span class="error" id="f2Err"></span>
<label>E-mail</label>
</div>
<div class="group">
<input type="text" class="move" name="f3" id="f3" /><span class="error" id="f3Err"></span>
<label>Message subject</label>
</div>
<div class="group">
<textarea type="text" class="move" name="f4" id="f4"></textarea><span class="error" id="f4Err"></span>
<label>Message</label>
</div>
<div class="submit-btn">
<input type="submit" value="SUBMIT" id="submit">
</div>
</form>
Thanks for any ideas.
Lets start with the first click function and the submit functionality, you haven't preventedDefault() to prevent the default method of the submit input you have provided, so you would need to preventDefault() of the event that is being sent in like so
$("#submit").click(function (e) {
e.preventDefault();
if (validate()) {
$.post($("#contact-form").attr("action"),
$("#contact-form :input").serializeArray(),
function (info) {
$("#f1Err").empty();
$("#f1Err").html(info);
$("#f2Err").empty();
$("#f2Err").html(info);
$("#f3Err").empty();
$("#f3Err").html(info);
$("#f4Err").empty();
$("#f4Err").html(info);
clear();
});
$("#contact-form").submit(function () {
return false;
});
}
});
as the method name shows, its "preventing the default behavior" from running. Next in your validation method, you are returing false after checking a field, so once that one of the validations fails, you are returning. maybe you should return a flag instead so like:
function validate() {
var flag = true;
if ($("#f1").val() == "") {
$("#f1Err").html("Name is requied");
flag = false;
}
if ($("#f2").val() == "") {
$("#f2Err").html("E-mail is requied");
flag = false;
}
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if (!re.test($("#f2").val())) {
$("#f2Err").html("Incorrect e-mail format");
flag = false;
}
if ($("#f3").val() == "") {
$("#f3Err").html("Message subject is requied");
flag = false;
}
if ($("#f4").val() == "") {
$("#f4Err").html("Message is requied");
flag = false;
}
return flag;
}
I think should solve your two biggest issues that you pointed out were wrong. (this is not necessarily the best implementation and variable names, i'll leave you to learn and improve on it)
I made a fiddle http://jsfiddle.net/3dnkvtb1. I set errors to false before validating each input, then for each check I set error to true if empty. Make sure to check the console for errors as you go. I added a console.log for each check. Then if no errors, send and clear your form.
$("#submit").click(function(event) {
event.preventDefault();
var hasError = false;
var re = /^(([^<>()[]\.,;:s#"]+(.[^<>()[]\.,;:s#"]+)*)|(".+"))#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/igm;
if ($("#f1").val() == "") {
hasError = true;
$("#f1Err").html("Name is required");
}
console.log($("#f1").val());
if ($("#f2").val() == "") {
hasError = true;
$("#f2Err").html("E-mail is required");
}
console.log($("#f2").val());
if (!re.test($("#f2").val())) {
hasError = true;
$("#f2Err").html("Incorrect e-mail format");
}
console.log($("#f3").val());
if ($("#f3").val() == "") {
hasError = true;
$("#f3Err").html("Message subject is required");
}
console.log($("#f3").val());
if ($("#f4").val() == "") {
hasError = true;
$("#f4Err").html("Message is required");
}
console.log($("#f4").val());
if(!hasError){
console.log('no errors');
//send your form
$.ajax({
url: 'url-here',
type: 'post',
dataType: 'json',
action : 'submit',
data: $('#contact-form').serialize(),
success: function(response) {
console.log(response);
//do something
clear();
}
});
} else {
console.log('something is up');
}
function clear() {
$("#contact-form :input").each(function () {
$(this).val("");
});
}
});
I'm trying to submit a HTML form, only when all the fields do not return false in the Javascript code.
My HTML looks like this, for simplicity I have just kept the name and email
<form method="post" action="RegistrationServlet" class="iform"
onsubmit="return sendForm();">
<ul><li><label for="YourName">*Your Name <span id="regNameErr"></span></label>
<input class="itext" type="text" name="YourName" id="YourName" /></li>
<li><br /><label for="YourEmail">*Your Email <span id="regEmailErr"></span></label>
<input class="itext" type="text" name="YourEmail" id="YourEmail" /></li>
<li><input type="submit" value="Submit" class="ibutton" name="SendaMessage"
id="SendaMessage" value="Send a Message!" readonly="readonly" /></li></ul></form>
The Javascript looks like this, again for simplicity I am just checking 2 fields:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.sendForm = function() {
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
$("#YourName").addClass("required");
window.scroll(0, 190);
$("#regNameErr").text("required");
return false;
}
if ($("#YourEmail").val() == "") {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
if (!isEmailValid($("#YourEmail").val())) {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Why is the sendForm() function not repeatedly being called to check that all fields are correct before submitting. Any ideas?
Also I understand that I can add a bounty after 2 days but I am not seeing any button on the editor.
Can you help?
sendForm is called only once per submit - this how it works, and there is no reason to call it multiple times.
If you want to have all your fields checked on submit - you should not return after each check. Instead you should postpone this action until the all fields are verified, and introduce some flag to remember results:
function() {
var formValid = true;
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
...
formValid = false;
}
if ($("#YourEmail").val() == "") {
...
formValid = false;
}
if (!isEmailValid($("#YourEmail").val())) {
...
formValid = false;
}
if (!formValid) {
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Side note. Have you considered any jQuery validation plugins for this? Might save you some implementation and maintenance efforts.
I have a form:
<form id="f3" method="post" action="interface_add.php">
<fieldset>
<input onclick="this.value=''" class="te3" type="text" name="f3a" value="title"/>
<input onclick="this.value=''" class="te3" type="text" name="f3b" value="url"/>
<a id="f3c" class='but' href="javascript:void(0)" onclick="i3()">Add</a>
<a id="f3d" class='but' href="javascript:void(0)" onclick="i3a()">Delete</a>
</fieldset>
</form>
and I use some Javsascript to "serialize" the element names and values like this:
function is(a)
{
var b='';
var c=document.forms[a].elements;
for(i=0;i<c.length;i++)
{
if(c[i].type=='checkbox'&&c[i].checked==false)
{
b+=c[i].name+"=NULL&";
}
else
{
b+=c[i].name+"="+c[i].value+"&";
}
}
b=b.slice(0,-1);
return b;
}
which I call from here:
function i3()
{
var a='';
a=is('f3');
However the return value I get from is() inserted into 'a' is
"undefined=undefined&f3a=title&f3b=url"
Funny thing is I had a similar problem previously but this was because I was not intializing 'a' which is why I broke this up, mostly out of paranoia that 'a' was not initialized properly.
Probably something simple I overlooked - but why is there undefined=undefined appearing.
It is coming from the <fieldset> element.
Just add a test for a name property inside the loop.
for(i=0;i<c.length;i++) {
if( c[i].name ) {
// your code
}
}
You'd probably like to skip all unnamed elements, like fieldset.
function is(a)
{
var b='';
var c=document.forms[a].elements;
for(i=0;i<c.length;i++)
{
if (c[i].name == undefined) continue; // skip all unamed elements
if (c[i].type == 'checkbox' && c[i].checked == false)
{
b += c[i].name + "=NULL&";
}
else
{
b += c[i].name + "=" + c[i].value + "&";
}
}
b = b.slice(0,-1);
return b;
}
Rather than using name, you can just get the checkboxes:
if(c[i].type=='checkbox')
{
if (c[i].checked==false)
{
b+=c[i].name+"=NULL&";
}
else
{
b+=c[i].name+"="+c[i].value+"&";
}
}
}
Of course you could just use submit buttons instead of links and let the form submit itself:
<input name="add" type="submit" value="Add">
<input name="delete" type="submit" value="Delete">
If the user clicks the Add button, a value is sent as ...add=Add..., if they click on the Delete button, then ...delete=Delete... is sent instead.
I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />