Show me if all inputs are empty - javascript

I need to build such that all four inputs must be specified any such if there is nothing in the name so it must appear that the it is as trouble is that nothing is written in the name.
I want to want out of this is that I will not have to use such can just create a user or send an email but it must have written something in every input form.
I have done like this:
<form action="#" method="post" name="kontakt_box">
<span id="myhint" class="info_box_kontakt"></span>
<br />
<label>Navn<br /><input type="text" name="navn" class="new" placeholder="Navn"></label><br />
<label>Efternavn<br /><input type="tel" name="efternavn" class="new" placeholder="Efternavn"></label><br />
<label>Email<br /><input type="email" name="email" class="new" placeholder="Email"></label><br />
<label>Tekst<br /><textarea name="tekst" cols="35" rows="10" class="new"></textarea></label><br />
<label><input type="submit" name="send" value="Send" class="new"></label>
</form>
Javascript here:
document.kontakt_box.navn.onfocus=function() {
document.getElementById('myhint').innerHTML = "Angive et navn!";
}
document.kontakt_box.navn.onblur=function() {
document.getElementById('myhint').innerHTML = "";
}
//efternavn
document.kontakt_box.efternavn.onfocus=function() {
document.getElementById('myhint').innerHTML = "Angive et efternavn!";
}
document.kontakt_box.efternavn.onblur=function() {
document.getElementById('myhint').innerHTML = "";
}
//email
document.kontakt_box.email.onfocus=function() {
document.getElementById('myhint').innerHTML = "Angive en email!";
}
document.kontakt_box.email.onblur=function() {
document.getElementById('myhint').innerHTML = "";
}
document.kontakt_box.send = function(){
alert('Husk noget tekst!');
return false;
}
it's my first javasciprt task to a page, so you just better with me that there may be errors or you think it's strange made​​.

Your last function may be something like this:
document.kontakt_box.onsubmit = function(){
var navn = document.kontakt_box.navn.value,
efternavn = document.kontakt_box.efternavn.value,
email = document.kontakt_box.email.value,
tekst = document.kontakt_box.tekst.value;
if(!navn || !efternavn || !email || !tekst) {
alert('Husk noget tekst!');
return false;
}
};
And add ; afret each callback function assignment.
Working example here http://jsbin.com/enovex/1/edit

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 make sure if everything is valid before submitting?

I have a HTML5 form and I'm using javascript to validate the form.
I have several 'if's checking the form and if it valid they change a variable ('pass') to true or false. They also display an error message. The problem is that even if just one thing is valid it changes the variable is true and I need it to only make pass true if everything else is valid.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<div>
<form name="register" action="register.php" method="POST" >
<label>First Name:</label>
<input type="text" id="firstName" name="firstName"><br />
<label id="warning_first"></label>
<br />
<label>Surname:</label>
<input type="text" id="lastName" name="lastName"><br />
<label id="warning_second"></label>
<br />
<label>Gender:</label>
<input type="radio" name="gender" value="Male" id="male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Other">Other
<input type="radio" name="gender" value="Prefer not to say"> Prefer not to say <br />
<label id="warning_third"></label>
<br />
<label>Email:</label>
<input type="email" id="email" name="email"> <br />
<label id="warning_fourth"></label>
<br />
<label>Confirm Email:</label>
<input type="email" id="confirmEmail" name="confirmEmail">
<br />
<label>Mobile:</label>
<input type="tel" id="mobileNumber" name="mobileNumber">
<br />
<label>Telephone:</label>
<input type="tel" id="telephoneNumber" name="telephoneNumber">
<br />
<input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
<input type="button" name="submit" value="Register" onclick="submitCheck();">
</form>
<script src="script.js"></script>
</div>
</body>
</html>
My JavaScript:
function submitCheck() {
var pass = false;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var genderTest = document.getElementsByName("gender");
var genderIf = false;
for (var a = 0; a < genderTest.length; a += 1) {
if (genderTest[a].checked) {
genderIf = true;
}
}
var emailCheck = document.getElementById("email").value;
if (firstName.length > 0) {
document.getElementById("warning_first").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_first").innerHTML = "This is required!";
pass = false;
}
if (lastName.length > 0) {
document.getElementById("warning_second").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_second").innerHTML = "This is required!";
pass = false;
}
if (genderIf) {
document.getElementById("warning_third").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_third").innerHTML = "This is required!"
pass = false;
}
if (emailCheck.length > 0) {
document.getElementById("warning_fourth").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_fourth").innerHTML = "Your email is too short!";
pass = false;
}
if (pass) {
console.log("OK");
} else {
console.log("NO");
}
}
As you can see, if the email is true, the console will log "OK" (which I am using to see if everything is valid"). How can I solve this so that it doesn't 'pass' to true if just the email is valid?
I am using a normal button instead of a submit button because of issues with the #onsubmit.
At the moment, you default pass to false and change it to true if any element passes the test.
Reverse your logic.
Set the default value of pass to true. Change it to false if any element fails its test.
Its simple, at the start of your code change your pass variable to have a value of 1 like so:
var pass = 1;
Now change the line of code in your IF statements where you have your pass variable. For a true condition set to this:
pass *= 1;
And for a false condition to this
pass *= 0;
This ensures that unless all IF conditions are satisfied your pass variable will not return a true state.

What condition for my javascript do I need? Its a script that pops up a dialogue box with form validation remarks for fields left blank

I have a form and a script that makes a dialogue box pop up if a field is left blank. The thing is, is that it only works if both fields are left blank. I'm trying to figure out how to get it to work correctly when and if one of the fields is left blank.
SCRIPT
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
if(sendMsg.mile.value=='' || isNaN(sendMsg.mile.value))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(sendMsg.location.value=='' || isNaN(sendMsg.location.value))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Form
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
Fixed it now, added input pattern to make sure only digits aswell as req'd on tags.Again I can't format the code in an answer so I'm adding another as I'd be here all night
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n in Numbers only\n";
}
if(location=='')
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="text" pattern="[0-9]+" class="form-control" data-validation-required-message="Please enter your Google Mileage" required id="mile" name="mile"/>
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" required placeholder="BUSINESS NAME" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
change:
isNaN(sendMsg.locaition.value)
to:
isNaN(sendMsg.location.value)
Try this
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="number" min="0" max="2000" class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value();
var location=document.getElementById("loc").value();
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(location=='' || isNaN(location))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>

Validation With Java Script and printing

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(); }
}

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