Validation With Java Script and printing - javascript

I have a form in HTML and that if the fields are left blank, the Javascript will print inside the fields error. Please can some one give me a piece of code that will validate the form and then will print Error on top of the form if its left blank and not inside the fields of the form?
My Form:
<form id="contact" onsubmit="checkContactForm(); return false;" onreset="resetForm();">
<p>Fill in the form below to send me a message!</p>
<div id="errormessage"></div>
<p>
<label for=""> </label>
<input type="text" name="" id="" onfocus="" />
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" onfocus="resetField(this);" />
</p>
<p>
<label for="email">E-mail address:</label>
<input type="text" name="email" id="email" onfocus="resetField(this);" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" rows="5" cols="25" onfocus="resetField(this);"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
My Javascript:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
}
}
if (!emptyFields) { myForm.submit(); }
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}

Since HTML5 there is a form-validation API (http://www.w3schools.com/js/js_form_validation.asp)
Here you can find a pretty good "tutorial": http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/

If I've understand you want the error will be printed in the #errormessage div, right?
If so you can simply do something like this:
function addError(str){
document.getElementById("errormessage").innnerHTML = document.getElementById("errormessage").innerHTML + str + "<br>";
}
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
addError(fiedlName+" is empty!");
}
}
if (!emptyFields) { myForm.submit(); }
}

Related

Why is my exception handling not catching?

This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}

How to get value result from the same form?

How can I take value results from this form?
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
And, JS is:
function sakupiPodatke(form){
var delovi = [];
var elementi = form.elements;
for(var i=0; i<elementi.length; i++){
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
var teloZahteva = sakupiPodatke(document.forma);
console.log(teloZahteva);
also Php file is simple:
<?php
$ime = $_POST["txtIme"];
$email = $_POST["txtEmail"];
?>
so...my question is how to read variable "teloZahteva" from JS in console.log?
Your code is running when the page first loads, before the user has had a chance to fill in the form. So it will display empty values in the console.
Put the code in an event listener that runs when the user clicks the submit button.
document.getElementById("dunja").addEventListener("submit", function(e) {
e.preventDefault();
var teloZahteva = sakupiPodatke(e.target);
console.log(teloZahteva);
});
function sakupiPodatke(form) {
var delovi = [];
var elementi = form.elements;
for (var i = 0; i < elementi.length; i++) {
var element = elementi[i];
var naziv = encodeURIComponent(element.name);
var vrednost = encodeURIComponent(element.value);
delovi.push(naziv + "=" + vrednost);
}
return delovi.join("&");
}
<form name="forma" method="post" action="index.php" id="dunja">
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" />
</p>
</form>
This displays the form values in the console instead of sending the form to PHP.
After my code I wrote this code and it says:
Uncaught ReferenceError: createXHR is not defined
function formPost(url, form, callback){
var xhr = createXHR();
var data = sakupiPodatke(form);
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 304){
callback(xhr.responseText);
}else{
alert("Greskica!");
}
}
};
xhr.send(data);;
}
function procesOdgovora(odgovor){
alert(odgovor);
}
formPost("index.php", document.forma, procesOdgovora);
<form name="forma" method="post" action="index.php" id="dunja" >
<p>
Ime: <input id="ime" type="text" name="txtIme" value="" />
</p>
<p>
Email: <input id="mail" type="text" name="txtEmail" value="" />
</p>
<p>
<input type="submit" name="btnProsledi" value="Prosledi" onclick="handleSubmit()" />
</p>
</form>
handleSubmit(){
var ime =getElementById('ime').value;
var mail =getElementById('mail').value;
}

Doing a web site with validation form

I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>

Clear out an error message instead of appending with javascript

In this HTML form that I have I would like to warn the user that he has to enter a level in the inputbox, if he clicks the button again I would like to clear off the error message and print it out again. I would like to also add more error messages but anything that I add as an error message appends to the end of the previous message.
function validateForm () {
var msg = ""
, result = true;
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
here's a jsbin
function validateForm () {
var result = true;
if (document.ExamEntry.name.value === "") {
document.getElementById('name-msg').innerHTML= "You Must Indicate Your Level";
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
Is this what are you looking for?
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value===""){
msg = document.createTextNode("You Must Indicate Your Level");
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild(msg)
document.getElementById('name-msg').style.color="red";
} else {
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"> </span>
<input type="submit" name="submit" value="Submit" onclick="validateForm();" />
</form>
You can clear the html like
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color = "red";
} else {
document.getElementById('name-msg').innerHTML = '';
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();" />
</form>
You may possibly use innerHTML:
function validateForm() {
var msg = "",
result = true;
if (document.ExamEntry.name.value === "") {
msg = "You Must Indicate Your Level";
}
document.getElementById('name-msg').innerHTML = msg;
}
#name-msg {
color: red;
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<br/>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>

Hide/clear input field with prototype

I have the following script:
if (Object.isUndefined(Axent)) { var Axent = { } }
Axent.SelfLabeledInput = Class.create({
initialize: function() {
var labelSelector = arguments[0] || 'label';
$$(labelSelector).findAll(function(l) {return (l.readAttribute('for') !== null)}).each(function(l){
l.hide();
$(l.readAttribute('for'))._value = l.innerHTML;
if ($(l.readAttribute('for')).value.empty()) {
$(l.readAttribute('for')).value = $(l.readAttribute('for'))._value
}
$(l.readAttribute('for')).observe('blur',function(e){if(Event.element(e).value == '') Event.element(e).value = Event.element(e)._value;});
$(l.readAttribute('for')).observe('focus',function(e){if(Event.element(e).value == Event.element(e)._value) Event.element(e).value = '';});
});
}
});
And the following form :
<form name="comform" action="#" method="post" id="commentform">
<div class="input">
<p>
<label for="comment">Type your comment here...</label>
<textarea name="comment" id="comment" rows="8" cols="10" class="" ></textarea>
</p>
</div>
<div class="input">
<p>
<label for="author">Name (required)</label>
<input type="text" name="author" id="author" size="22" class=""/>
</p>
</div>
<div class="input">
<p>
<label for="email">Email (gravatar enabled) (required)</label>
<input type="text" name="email" id="email" size="22" class=""/>
</p>
</div>
<div class="input">
<p>
<label for="url">Website (optional)</label>
<input type="text" name="url" id="url" size="22" />
</p>
</div>
<div class="submit">
<input type="submit" name="submit" id="sub" value="Leave comment" />
<input type="hidden" name="comment_post_ID" id="hidden" value="">
</div>
</form>
<script type="text/javascript">
//<![CDATA[
new Axent.SelfLabeledInput('#commentform label');
//]]>
</script>
I want to write a function from this script such that when I press the submit on this form, and an input field is focused, it hides/clears it, so it doesn't get submitted to the database.
This works with the latest Prototype lib. I don't know any JavaScript, so I need your help. I'm using this form for my WordPress comments area.
I finally got it to work! Here's the final code if someone else wants to run it:
if (Object.isUndefined(Axent)) { var Axent = { } }
Axent.SelfLabeledInput = Class.create({
initialize: function() {
var labelSelector = arguments[0] || 'label';
$$(labelSelector).findAll(function(l) {return (l.readAttribute('for') !== null)}).each(function(l){
l.hide();
var el = $(l.readAttribute('for'));
el._value = l.innerHTML;
if (el.value.empty()) {
el.value = el._value
}
el.observe('blur',function(e){if(Event.element(e).value == '') Event.element(e).value = Event.element(e)._value;});
el.observe('focus',function(e){if(Event.element(e).value == Event.element(e)._value) Event.element(e).value = '';});
$(el.form).observe( 'submit', (function(thisel) { return function(e) {
if( thisel.value == thisel._value ) { thisel.value = '' }
}})(el));
});
}});
You don't have to worry, labels won't get submitted.
This script will remove the labels from the DOM on submit tho. It has to be run after the DOM is loaded (well, at least the form) and if your form elements are inside the labels they will disappear too!
document.getElementById( 'commentform' ).onsubmit = function() {
var labels = this.getElementsByTagName( 'label' );
while( labels[0] ) {
labels[0].parentNode.removeChild( labels[0] );
}
return true;
}
This is not a prototype script. It's Plain Old Javascript.
The elements are pre-filled with the label text. On focus the default text disappears and reappears on blur if the element is still empty.
You could try this. I don't use prototype, so it's a guess in places.
if (Object.isUndefined(Axent)) { var Axent = { } }
Axent.SelfLabeledInput = Class.create({
initialize: function() {
var labelSelector = arguments[0] || 'label';
$$(labelSelector).findAll(function(l) {return (l.readAttribute('for') !== null)}).each(function(l){
l.hide();
var el = $(l.readAttribute('for'));
el._value = l.innerHTML;
if (el.value.empty()) {
el.value = el._value
}
el.observe('blur',function(e){if(Event.element(e).value == '') Event.element(e).value = Event.element(e)._value;});
el.observe('focus',function(e){if(Event.element(e).value == Event.element(e)._value) Event.element(e).value = '';});
$(el.form).observe( 'submit', (function(thisel) { return function(e) {
if( thisel.value == thisel._value ) { thisel.value = '' }
}})(el));
});
}

Categories