Form Validation using JavaScript? - javascript

I'm trying to use form validation using JavaScript, however I don't seem to get any response, not even an alert even though it's there.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="2013.php" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
</html>

use === or == for condition checking in javascript.
if(document.getElementById('name').value === ""){
alert("enter something valid");
return false;
}

You have to use == for comparison.= is used for assigment
if(document.getElementById('name').value == ""){
alert("enter something valid");
return false;
}

Working Demo
Here Your issue is regarding if condition only! You must use == OR === in JavaScript for comparison.
Below is corrected script!
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
If you remove Or avoid return false, form will postback Even if Validation fails! So, return false means, exiting from function after if is must, and which is missed out in another answer!!

You are using = that is assignment operator, use == comparison operator that's work fine
<head>
<title>Example Form</title>
<script type="text/javascript">
function CheckForBlank() {
if(document.getElementById('name').value=="") {
alert("enter something valid");
return false;
}
}
</script>
</head>
<body>
<form method="post" onsubmit="return CheckForBlank();">
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
Email: <input type="text" name="email" id="email"/>
<p><input type="submit" value="Submit" /></p>
</form>
</body>

I can't believe I've never realised this until now, although if you attach your Javascript to the form submission event, instead of the button submit event; the normal browser verification works (ie. input[type="email], required="required", etc.).
Works in Firefox & Chrome.
// jQuery example attaching to a form with the ID form
$(document).on("submit", "#form", function(e) {
e.preventDefault();
console.log ("Submitted! Now serialise your form and AJAX submit here...");
})

I have done a better way to do form validation using bootstrap. You can take a look at my codepen http://codepen.io/abhilashn/pen/bgpGRw
var g_UnFocusElementStyle = "";
var g_FocusBackColor = "#FFC";
var g_reEmail = /^[\w\.=-]+\#[\w\.-]+.[a-z]{2,4}$/;
var g_reCell = /^\d{10}$/;
var g_invalidFields = 0;
function initFormElements(sValidElems) {
var inputElems = document.getElementsByTagName('textarea');
for(var i = 0; i < inputElems.length; i++) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
/* Add the code for the input elements */
inputElems = document.getElementsByTagName('input');
for(var i = 0; i < inputElems.length; i++) {
if(sValidElems.indexOf(inputElems[i].getAttribute('type') != -1)) {
com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
}
}
/* submit handler */
com_abhi.EVENTS.addEventHandler(document.getElementById('form1'), 'submit' , validateAllfields, false);
/* Add the default focus handler */
document.getElementsByTagName('input')[0].focus();
/* Add the event handlers for validation */
com_abhi.EVENTS.addEventHandler(document.forms[0].firstName, 'blur', validateFirstName, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].email, 'blur', validateEmailAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].address, 'blur', validateAddress, false);
com_abhi.EVENTS.addEventHandler(document.forms[0].cellPhone, 'blur', validateCellPhone, false);
}
function highlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = g_FocusBackColor;
}
}
function unHightlightFormElement(evt) {
var elem = com_abhi.EVENTS.getEventTarget(evt);
if(elem != null) {
elem.style.backgroundColor = "";
}
}
function validateAddress() {
var formField = document.getElementById('address');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpAddress');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('addressIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('addressErrorMsg').innerHTML = "Please enter your address";
}
return ok;
}
}
function validateFirstName() {
var formField = document.getElementById('firstName');
var ok = (formField.value != null && formField.value.length != 0);
var grpEle = document.getElementById('grpfirstName');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('firstNameIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('firstNameErrorMsg').innerHTML = "Please enter your first name";
}
return ok;
}
}
function validateEmailAddress() {
var formField = document.getElementById('email');
var ok = (formField.value.length != 0 && g_reEmail.test(formField.value));
var grpEle = document.getElementById('grpEmail');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('EmailIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('emailErrorMsg').innerHTML = "Please enter your valid email id";
}
}
return ok;
}
function validateCellPhone() {
var formField = document.getElementById('cellPhone');
var ok = (formField.value.length != 0 && g_reCell.test(formField.value));
var grpEle = document.getElementById('grpCellPhone');
if(grpEle != null) {
if(ok) {
grpEle.className = "form-group has-success has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-ok form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "";
}
else {
grpEle.className = "form-group has-error has-feedback";
document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-remove form-control-feedback";
document.getElementById('cellPhoneErrorMsg').innerHTML = "Please enter your valid mobile number";
}
}
return ok;
}
function validateAllfields(e) {
/* Need to do it this way to make sure all the functions execute */
var bOK = validateFirstName();
bOK &= validateEmailAddress();
bOK &= validateCellPhone();
bOK &= validateAddress();
if(!bOK) {
alert("The fields that are marked bold and red are required. Please supply valid\n values for these fields before sending.");
com_abhi.EVENTS.preventDefault(e);
}
}
com_abhi.EVENTS.addEventHandler(window, "load", function() { initFormElements("text"); }, false);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<h1 class="text-center">Interactive form validation using bootstrap</h1>
<form id="form1" action="" method="post" name="form1" class="form-horizontal" role="form" style="margin:10px 0 10px 0">
<div id="grpfirstName" class="form-group">
<label for="firstName" class="col-sm-2 control-label"><span class="text-danger">* </span>First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="firstName" placeholder="Enter first name">
<span id="firstNameIcon" class=""></span>
<div id="firstNameErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastName" placeholder="Enter last name">
</div>
</div>
<div id="grpEmail" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Email </label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter email">
<span id="EmailIcon" class=""></span>
<div id="emailErrorMsg" class="text-danger"></div>
</div>
</div>
<div id="grpCellPhone" class="form-group">
<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Cell Phone </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="cellPhone" placeholder="Enter Mobile number">
<span id="cellPhoneIcon" class=""></span>
<div id="cellPhoneErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group" id="grpAddress">
<label for="address" class="col-sm-2 control-label"><span class="text-danger">* </span>Address </label>
<div class="col-sm-10">
<textarea id="address" class="form-control"></textarea>
<span id="addressIcon" class=""></span>
<div id="addressErrorMsg" class="text-danger"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
</div> <!-- End of row -->
</div> <!-- End of container -->
Please check my codepen to better understand code.

Related

Regular Expression always false

So I am writing some javascript to check if a user inputs a gmail address.
At the moment I have the code thats below, but no matter what I do it is giving me false. even when the input has #gmail.com...I feel that the mistake is how I am grabbing the user input in a variable and then testing it with test().
Javascript:
<script>
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {
}
}
</script>
html
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input
type="text"
class="form-control col-sm-1"
id="inputEmail"
placeholder="username#gmail.com"
/>
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>
You need to check the value of the input, var emailMatch = gmailPatt.test(email.value);
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email.value);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {}
}
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input type="text" class="form-control col-sm-1" id="inputEmail" placeholder="username#gmail.com" />
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>

document.getElementById in amp-script code giving element data differently

I am using AMP to develop my website. In that, I am using amp-script. When I use document.getElementById, it is giving the element data differently. I am looking for some properties like value etc. in it. But, can't those. See the below screenshot to look at the contents.
Please help me solve this.
Thank you...
EDIT: Added code snippet
HTML:
<form action="click" target="_blank" name="contact_form" id="contact_form" class="contact-form__block">
<div class="form__group">
<label for="message" class="form__label message_label">The idea that is brewing in your mind?
*</label>
<textarea name="message" id="form__textarea" class="form__textarea"></textarea>
</div>
<div class="form__group">
<label for="name" class="form__label name_label">Name </label>
<input type="text" name="name" id="form__name" class="form__input name" value="" autocomplete="off">
</div>
<div class="form__groups">
<div class="form__group">
<label for="phone" class="form__label phone_label">Phone Number </label>
<input type="text" name="phone" id="form__phone" class="form__input phone" value=""
autocomplete="off">
<!-- error message start -->
<!-- <div class="form__error e_mail">Please enter all required details.</div> -->
<!-- error message end -->
</div>
<div class="form__group">
<label for="mail" class="form__label email_label">Email *</label>
<input type="text" name="mail" id="form__mail" class="form__input mail">
</div>
</div>
<div class="form__group">
<div class="form-button__block">
<button type="button" name="submit" class="form__submit" id="form-submit">
<div class="arrow__btn-link-text">Let's Connect</div>
<amp-img src="stroke-arrow-right.svg" height="1" width="1"
alt="arrow right icon" class="arrow__btn-icon">
</button>
<!-- <div class="button--border"></div> -->
</div>
<div class="error_box">
<span class="error_message"></span>
</div>
</div>
</form>
JS:
var form = document.getElementById("form-submit"), msg;
form.addEventListener("click", function(event) {
event.preventDefault();
if (document.getElementById('form__textarea').value == '') {
msg = false;
} else {
msg = true;
}
if (document.getElementById('form__mail').value == '') {
email = false;
} else {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var validEmail = emailReg.test(document.getElementById('form__mail').value);
if (!validEmail) {
email = false;
} else {
email = true;
}
}
if (document.getElementById('form__phone').value == '') {
phone = true;
document.getElementById('form__phone').value = "";
} else {
var phoneReg = /^([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
var validPhone = phoneReg.test(document.getElementById('form__phone').value);
if (!validPhone) {
phone = false;
} else {
phone = true;
}
}
if (document.getElementById('form__name').value == '') {
document.getElementById('form__name').value = "";
} else {
name = true;
}
if (!msg || !email || !phone) {
console.log("Error in formmmmmmmmmmmmm");
return false;
} else {
console.log("valid formmmmmmmmmmmmmmmmmmmmmm");
}
});

Trying to store a completed form into an array

I'm creating a registration page and am currently attempting to store the inputs of the form into an array. I'm using
var form_inputs = document.getElementsByClassName("form_input");
to store the inputs in the same place, however if I try to alert form_inputs to test if anything is actually being stored, it just alerts "Undefined".
function validate_form(event) {
var forename = document.getElementById("forename");
var surname = document.getElementById("surname");
var username = document.getElementById("username");
var password = document.getElementById("password");
var re_password = document.getElementById("re_password");
var email = document.getElementById("email");
var errors = 0
var special_chars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var form_inputs = document.getElementsByClassName("form_input");
if (forename.value == "") {
//document.getElementById("forename").style.background = "red";
forename_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < forename.value.length; i++) {
if (special_chars.indexOf(forename.value.charAt(i)) != -1) {
forename_chars.style.visibility = 'visible'
}
}
if (surname.value == "") {
//document.getElementById("surname").style.background = "red";
surname_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < surname.value.length; i++) {
if (special_chars.indexOf(surname.value.charAt(i)) != -1) {
surname_chars.style.visibility = 'visible'
}
}
if (username.value == "") {
//document.getElementById("username").style.background = "red";
username_confirmation.style.visibility = 'visible';
var errors = errors + 1
} else
for (var i = 0; i < username.value.length; i++) {
if (special_chars.indexOf(username.value.charAt(i)) != -1) {
username_chars.style.visibility = 'visible'
}
}
if (password.value == "") {
//document.getElementById("password").style.background = "red";
pass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (password.value != re_password.value) {
//document.getElementById("re_password").style.background = "red";
repass_confirmation.style.visibility = 'visible';
var errors = errors + 1
}
if (email.value == "") {
//document.getElementById("email").style.background = "red";
var errors = errors + 1
}
if (errors != "0") {
alert("Whoops! Looks like you didn't enter your details properly");
console.log(form_inputs);
event.preventDefault(); // Prevent the form from submitting
}
if (!email.value.includes("#") || !email.value.includes(".")) {
//document.getElementById("email").style.background = "blue";
email_confirmation.style.visibility = 'visible';
return false;
}
return (true);
}
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
<link rel="stylesheet" type="text/css" href="Login Form CSS.css">
<script src="Registration function.js" defer></script>
<body>
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="login-form">
<div id="forename_confirmation"> Please fill in this box </div>
<div id="forename_chars"> Don't use special characters</div>
<p>Forename
<p>
<input class="form_input" type="text" name="forename" id="forename" placeholder="Enter Forename here">
<div id="surname_confirmation"> Please fill in this box </div>
<div id="surname_chars"> Don't use special characters</div>
<p>Surname
<p>
<input class="form_input" type="text" name="surname" id="surname" placeholder="Enter Surname here">
<div id="username_confirmation"> Please fill in this box </div>
<div id="username_chars"> Don't use special characters</div>
<p>Username
<p>
<input class="form_input" type="text" name="username" id="username" placeholder="Enter Username here">
<div id="pass_confirmation"> Please fill in this box </div>
<div id="pass_chars">Don't use special characters</div>
<p>Password
<p>
<input class="form_input" type="password" name="password" id="password" placeholder="Enter Password here">
<div id="repass_confirmation"> Passwords do not match </div>
<p>Re-enter Password
<p>
<input class="form_input" type="password" name="re_password" id="re_password" placeholder="Re-enter your password here">
<div id="email_confirmation"> Please enter a valid email </div>
<p>Email
<p>
<input class="form_input" type="email" name="email" id="email" placeholder="Enter Email here">
<!--
<p>Gender<p>
<input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="validate_form(event)" type="Submit" value="True" name="button-submit"> Submit </button>
<br />
<br />
Forgot your password?
<br />
Already got an account?
<br /><br />
</form>
<!-- <button onclick="validate_form()" type="submit"> Validate </button> -->
</div>
</body>
</head>
<script>
forename_confirmation.style.visibility = 'hidden'
forename_chars.style.visibility = 'hidden'
surname_confirmation.style.visibility = 'hidden'
surname_chars.style.visibility = 'hidden'
username_confirmation.style.visibility = 'hidden'
username_chars.style.visibility = 'hidden'
pass_confirmation.style.visibility = 'hidden'
pass_chars.style.visibility = 'hidden'
repass_confirmation.style.visibility = 'hidden'
email_confirmation.style.visibility = 'hidden'
</script>
</body>
Array.from(document.getElementsByClassName("form_input")).forEach(
function(element, index, array) {
alert(element.innerHTML)
}
);
this will alert you of those elements

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

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