Set focus on input text where ID not defined - javascript

I want to set focus each time on the textbox if alert message is prompted. How should I deal where I use that javascript function for multiple times. Here is my js code
function validateLandline(landfield) {
var reg = /\d{5}([- ]*)\d{6}/;
if (reg.test(landfield.value) == false) {
jAlert('Kindly enter valid landline no', 'INFORMATION');
return false;
landfield.focus();
}
return true;
}
and textbox html
<input type="text" id="txtStoreSiteL1" onchange="validateLandline(this);" maxlength="20" />

Based on the comments, I have created a small snippet below:
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
$('input').on('input focusout', function() {
$(this).removeClass('error');
if (!validateEmail($(this).val())) {
$(this).addClass('error').focus();
}
});
.error {
border: 2px solid #d00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtStoreSiteL1" maxlength="20" />
<input type="text" id="txtStoreSiteL2" maxlength="20" />

Related

Form submits even when there is an invalid input

I am trying to validate the text input in my html. I only want alphabets and spaces. In the beginning, the validation worked but now it is not and I cannot seem to find the problem. It still submits the form with the invalid field. Please see the code below
index.html
<div class="full-form">
<form class=form-info action="cv.html" onsubmit="return handlesubmit()" >
<div class="f-header">
SIGN UP
</div>
<div class="bdetails">
<label for="fname">First Name</label><br>
<input type="text" name="fname" id="f_name" placeholder="First Name" onfocus="checkFName()" onblur="BlurFName()" required><br>
<p class="error_message" id="First_em">Name must contain only alphabets(A-Z)</p>
</div>
<script type="text/javascript" src="test.js"></script>
</form>
test.js
function checkData(){
if(BlurFName()){
}
return false;
}
function handlesubmit(){
checkData();
passvalue();
}
/*
Function to check if the name inputted is valid when the input is focused
*/
function checkFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(!fname.value.match(name_len)){
document.getElementById("First_em").style.display = "inline";
return true;
}
};
/*
Function to check if the name inputted is valid when the input is blurred
*/
function BlurFName(){
let name_len=/^[A-Za-z]+$/;
let fname= document.getElementById("f_name");
if(fname.value.match(name_len)){
document.getElementById("First_em").style.display = "none";
return false;
}
};
With function handlesubmit you need to return false or true.
I suggest use
e.preventDefault();
to easier handle Form submiting
You are not returning anything from your validation method. You need to do something like this:
function validateName () {
const inp = document.getElementById("fname");
const isValid = inp.value.trim().length > 0;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validateGuess () {
const inp = document.getElementById("guess");
const isValid = +inp.value.trim() > 10;
inp.classList.toggle('error', !isValid);
return isValid;
}
function validate () {
const isNameValid = validateName();
const isGuessValid = validateGuess();
return isNameValid && isGuessValid;
}
.error { border-color: red; }
<form onsubmit="return validate()">
<label for="fname">name</label> <input type="text" name="fname" id="fname" /><br/>
<label for="guess">guess</label> <input type="number" name="guess" id="guess" />
<button>Submit</button>
</form>

JavaScript Form Validation Function: Looping each item

I have a list of form input elements on which I want to run a loop. From the result, I need to run a few conditional statements so that I can validate them using their name attributes. I've used jQuery for that and used .each method for looping through them. Thus I can add/remove class name to invalid input elements.
It's little difficult to describe in words. But the code block bellow will make sense:
JSFiddle
function formValid() {
var valid = true;
$('form input').each(function() {
if ($(this).val() == '') {
valid = false;
$(this).addClass('red-border');
} else if (true /* if "tel" is not a number */ ) { // <- here I want to validate using input name attribute
valid = false;
$(this).addClass('red-border');
} else {
$(this).removeClass('red-border');
}
});
return valid;
}
$('form').on('submit', function(event) {
event.preventDefault();
if (formValid()) {
alert('Yay!');
}
});
.red-border {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<p>
<input type="text" name="name">
</p>
<p>
<input type="text" name="tel">
</p>
<p>
<input type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
Check out the fiddle
https://jsfiddle.net/t9ayvken/
CSS:
.red-border {
border-color: red;
}
HTML:
<form action="#">
<p>
<input class="must-validate" type="text" name="name">
</p>
<p>
<input class="must-validate" type="text" name="tel">
</p>
<p>
<input class="must-validate" type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
JQuery:
/*validation functions for each input type*/
function validateName(event){
var $this = $(this);
/* validation is done here */
if(false){
$this.removeClass('red-border');
}
else {
/* not valid*/
$this.addClass('red-border');
}
}
function validateTel(event){
}
function validateEmail(event){
}
/*add validation event handlers*/
$(document).on('validate','[name="name"]',validateName);
$(document).on('validate','[name="tel"]',validateTel);
$(document).on('validate','[name="email"]',validateEmail);
function formValid() {
var valid = true;
/*Trigger validation events for all required inputs*/
$('input.must-validate').trigger('validate');
/* After validation is complete check to see if any are invalid */
if( $('input.must-validate.red-border').length ){
alert('the form is invalid');
valid = false;
}
return false;
//return valid;
}
$('form').on('submit', function(event) {
event.preventDefault();
if ( formValid() ) {
alert('Yay!');
}
});
I suggest returning a list of errors instead of a boolean flag.
function formValid() {
var errorMsgs = [];
$('form input').each(function() {
var msg = [],
val = $(this).val();
// Check blanks
if (val == '')
msg.push( `${$(this).attr('name')} is blank`);
// Check numbers
if ($(this).attr('name') === 'tel' && isNaN(val))
msg.push( `${$(this).attr('name')} is not a number`);
// Handle results
if (msg.length > 0){
errorMsgs.push(...msg);
$(this).addClass('red-border');
} else {
$(this).removeClass('red-border');
}
});
return errorMsgs;
}
$('button').on('click', function(event) {
var errors = formValid();
if (errors.length === 0) {
alert('Yay!');
} else {
alert(errors.join('\r'));
}
});
.red-border {
border-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<p>
<input type="text" name="name">
</p>
<p>
<input type="text" name="tel">
</p>
<p>
<input type="text" name="email">
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>

Force user to fill all fields before enabling form submit

I have a form containing various fields.
See jsFiddle demo.
My aim is to enable the submit button only when the user has filled in all fields.
So far, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too before submit button is enabled.
jQuery("input[type='text']").on("keyup", function () {
if (jQuery(this).val() != "" ) {
if (jQuery("#titlenewtide").val() != '')
{
jQuery("#subnewtide").removeAttr("disabled");
}
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Note that I am loading the JavaScripts in my footer.
Make the changes take effect after changing inputs values:
On each input change, test the values of other inputs and checked state of radio, if all inputs has been entered it will make the submit button enabled:
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
Demo:
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Also it uses the form id="myForm", so you can use it to validate only specific forms in your pages.
Note: This is tested and working on Chrome, Firefox and IE.
EDIT:
Make the changes take effect when we type in the inputs:
In the previous code we are using onchange event handler to call the function so it's only called when we click outside a given input (after change).
To perform the call automatically when the user enters a character in a field (the last one) we need to use the onkeyup event so we don't need to click outside of it.
This is the changed code you need :
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Use this code below. On each input, it will check all the form fields by using this function validate().
jQuery("input[type='text'], textarea").on("input", function () {
var isValid = validate();
if (isValid) {
jQuery("#subnewtide").removeAttr("disabled");
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
function validate() {
var isValid = true;
$('input, textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
Fiddle
Update
To make it validate if the form has id="new_tide" and fix about the radio button.
$("input[type='text'], textarea").on("change input", function() {
validate($(this));
});
$("input:radio[name='category']").on("change", function() {
validate($(this));
});
function validate(self) {
if (self.parents("form:first").attr("id") == "new_tide") {
var isValid = true;
$('input[type="text"], textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
if (!$("input:radio[name='category']").is(':checked'))
isValid = false;
if (isValid) {
$("#subnewtide").removeAttr("disabled");
} else {
$("#subnewtide").attr("disabled", "disabled");
}
}
}
Fiddle
Here's how you can do it:
$(document).ready(function () {
var $inputs = $("#new_tide input:not([type=hidden]), #new_tide textarea");
$inputs.on("input change", function () {
valid = true;
$inputs.each(function () {
valid *= this.type == "radio" ? this.checked : this.value != "";
return valid;
});
$("#subnewtide").prop("disabled", !valid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
Hidden: <input type="hidden">
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Try utilizing .siblings() , .map() to compile values of form elements , Array.prototype.every() to return Boolean representation of input , textarea values , set disabled property of form input[type=submit] element
$("form *[required]").on("input change", function(e) {
$(this).siblings("[type=submit]").prop("disabled"
, !$(this).siblings(":not([type=submit])").add(this).map(function(_, el) {
return el.type === "radio" ? el.checked : el.value
}).get().every(Boolean)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description" required></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
By far the easiest, would be to rely on the HTML5 validation you're already using.
You'd have to add required to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input selector and setting the property, like so
$(':input:not(#subnewtide)').prop('required', true)
We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.
Then we'll listen for the input event, which covers all sorts of inputs, like typing, pasting etc, and the change event as well to cover the radio button.
Using form.checkValidity() tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled property of the submit button.
All together it looks like this, and that's all you need, a few lines of really simple code
$(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
$('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
});
FIDDLE
If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill
My solution is base on standard JavaScript.
HTML form
<form action="#" method="post" id="new_tide" name="form1">
Title: <input onkeyup="myBtnActivator(1)" id="titlenewtide" name="title" type="text" required> <br>
Description: <textarea onkeyup="myBtnActivator(2)" id="description" name="description"></textarea> <br>
Tag: <input id="newtag" onkeyup="myBtnActivator(3)" name="newtag" type="text" required> <br>
Category: <input name="category" onchange="myBtnActivator(4)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
JavaScript
<script>
document.getElementById("subnewtide").disabled = true;
var input1 = false;
var input2 = false;
var input3 = false;
var input4 = false;
function myBtnActivator(i) {
switch (i) {
case 1:
input1 = true;
if (document.form1.title.value == "")
input1 = false;
break;
case 2:
input2 = true;
if (document.form1.description.value == "")
input2 = false;
break;
case 3:
input3 = true;
if (document.form1.newtag.value == "")
input3 = false;
break;
case 4:
input4 = true;
if (document.form1.subnewtide.value == "")
input4 = false;
break;
}
trigger();
}
function trigger() {
if (input1 == true && input2 == true && input3 == true && input4 == true) {
document.getElementById("subnewtide").disabled = false;
} else {
document.getElementById("subnewtide").disabled = true;
}
}
</script>
Why don't you use jquery validate . It's a good plugin .
The logic works like, any change in the form it will check the form is valid or not. And also using the errorplacement function it will disable the default error message also.
$().ready(function() {
// validate signup form on keyup and submit
$("#contactForm").validate({
rules: {
title: "required",
description: {
required: true
},
newtag: {
required: true
},
category: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#contactForm').change(function() {
if ($("#contactForm").valid()) {
$("#subnewtide").removeAttr("disabled");
}
});
});
Fiddle
There's actually a pretty easy approach. I'm using native JavaScript, but I think it is applicable in jQuery as well:
var form = document.getElementById("new_tide");
form.onchange = function onChange() {
var enable = true;
var inputs = form.getElementsByTagName("input");
var textareas = form.getElementsByTagName("textarea");
for (var i in inputs) {
enable = enable && inputs[i].value != "";
}
for (var i in textareas) {
enable = enable && textareas[i].value != "";
}
enable = enable && textarea.value != "";
document.getElementById("subnewtide").disabled = !enable;
}
The change event on form is always called, when any input or textarea element was changed (click in element, type, click somewhere else or lose focus).
Edit:
Regarding hidden fields, you can exclude them by surrounding the enable calculation with an if-condition:
if (!inputs[i].hidden) {
enable = enable && inputs[i].value != "";
}
Note:
This will work in any browser (even Internet Explorer 5.5). Check on MDN:
for ..in Loop
element.getElementsByTagName()
document.getElementById()
Thought I might chip in. Assuming as little as possible.
jQuery("input, textarea").on("keyup click", function () { // going vanilla after easy-mode attach
var sub = document.getElementById('subnewtide');
if (require_all(find_form(this))) {
sub.removeAttribute('disabled');
sub.disabled = false;
} else {
sub.setAttribute('disabled', 'disabled');
sub.disabled = true;
}
});
function concat(a, b) { // concating Array-likes produces Array
var slice = [].slice; // not assuming Array.prototype access
return [].concat.call(
slice.call(a, 0),
slice.call(b, 0)
);
}
function find_form(e) { // shim input.form
if (e) do {
if (e.tagName === 'FORM') return e;
} while (e = e.parentNode);
return null;
}
function require_all(form, dontIgnoreHidden) { // looks at textareas & inputs (excluding buttons)
var inp = concat(form.getElementsByTagName('input'), form.getElementsByTagName('textarea')),
rad = {}, // not assuming Object.create
i, j,
has = {}.hasOwnProperty; // not assuming Object.prototype access
for (i = 0; i < inp.length; ++i) {
switch ((inp[i].type || '').toLowerCase()) {
default: // treat unknown like texts
case 'text':
if (!inp[i].value) return false; break;
case 'checkbox':
if (!inp[i].checked) return false; break;
case 'radio':
j = inp[i].getAttribute('name');
if (!rad[j]) rad[j] = inp[i].checked;
break;
case 'hidden':
if (dontIgnoreHidden && !inp[i].value) return false; break;
case 'button':
case 'submit':
break;
}
}
for (j in rad) if (!has || has.call(rad, j)) // not assuming hasOwnProperty
if (!rad[j]) return false;
return true;
}
Here is a quick way to accomplish that. It involves attaching a change event listener to :radio and :checkbox elements and an input event listener to other elements. These can both use a common predefined handler that will count the number of unfilled element each time each of these events fires on the appropriate element.
function checkForm() {
//define and initialize variables
var unfilled = 0,
form = $(this.form);
//disable submit button if enabled
$(':submit', form).prop('disabled', true);
//count number of unfilled elements
$(':input', form).each(function() {
if( $(this).is(':radio,:checkbox') ) {
$('input[name=' + this.name + ']:checked').length || unfilled++;
} else {
$('[name=' + this.name + ']').val() || unfilled++;
}
});
//enable submit button if no unfilled element is found
unfilled || $(':submit', form).prop('disabled', false);
}
//set up event listeners to fire above handler
$(':text,textarea,select').on('input', checkForm);
$(':radio,:checkbox').on('change', checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Use this html<br>
HTML:
<br>
<pre>
<form action="#" method="post" id="">
Title: ##<input id="titlenewtide" type="text" name="title" required>
Description: <textarea name="description" id="description"></textarea>
Tag: <input id="newtag" type="text" name="newtag" required>
Category: <input type="checkbox" onclick="validate()" name="category" id="cate"value="19" required > Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
</pre>
validation code:<br>
//on each key up function intiate the function validate
<pre>
jQuery("input[type='text']").on("keyup", function () {
validate();
});
jQuery("#description").on("keyup", function () {
validate();
});
function validate(){
jQuery("input[type='text']").each(function(){
if (jQuery(this).val() != "" )
{
if((jQuery("#description").val() !="") && (jQuery("#cate").is(':checked')))
{
jQuery("#subnewtide").removeAttr("disabled");
}
else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
}
});
}
</pre>
you can find the fiddle in : https://jsfiddle.net/s8uv2gkp/
Maytham Fahmi's relatively easy solution can be made even easier by passing this.name.
<form action="#" method="post" id="new_tide" name="form1">
<input onkeyup="myBtnActivator(this.name)" name="title" type="text" required> <br>
<textarea onkeyup="myBtnActivator(this.name)" name="description"></textarea> <br>
<input id="newtag" onkeyup="myBtnActivator(this.name)" name="newtag" type="text" required> <br>
<input name="category" onchange="myBtnActivator(this.name)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
this refers to the DOM object that called the function. So the switch can just directly take the name, or the value, or anything else you can pass with DOM.
myBtnActivator(n)
{
switch(n)
{
case "title":
break;
case "description":
break;
case "newtag":
break;
case "category":
break;
}
}

Validate optional form fields with default values

Here's my javascript:
$("#cname, #cemail, #curl, #ccomment").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("");
}
}).blur(function() {
if( !this.value.length ) {
$(this).val(this.defaultValue);
}
});
$.validator.addMethod("noName", function(value, element) {
return value != element.defaultValue;
}, "Please enter your name.");
$.validator.addMethod("noComment", function(value, element) {
return value != element.defaultValue;
}, "Please enter your comment.");
$("#commentForm").validate();
The actual form:
<form id="commentForm" action="">
<p>
<input id="cname" name="name" size="25" class="required noName" value="Name">
</p>
<p>
<input id="cemail" name="email" size="25" class="email" value="Email">
</p>
<p>
<input id="curl" name="url" size="25" class="url" value="URL">
</p>
<p>
<textarea id="ccomment" name="comment" rows="5" cols="35" class="required noComment">Comment</textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</form>
And here's a test: http://dl.dropbox.com/u/4017788/Labs/form-validation.html
If you click the submit button, you get error messages on Email and URL fields while they are optional. How can I prevent it?
Simple approach: add an igonre class to Email and URL fields and removeClass / addClass on focus / blur. Test:
http://dl.dropbox.com/u/4017788/Labs/form_validation.html
see validate options for more information.
Alternatively you can completely get rid of the class attribute and then:
on focus >> this.className = 'url'
on blur >> this.className = ''
without changing the validate call.
You can't use the classes 'url' and 'email' for those two form fields, because the plugin is going to try and validate them because they are 'reserved' classes in the plugin . I would suggest trying doing something like this for both the email and url fields.
I haven't tried this, but it suggests that you can custom, but not required field.
You could use the HTML5 placeholder element all the same, but test for placeholder support and then polyfill for it if not available, for example
//test
function placeholderIsSupported() {
var test = document.createElement('input');
return ('placeholder' in test);
}
//polyfill
if(!(placeholderIsSupported())) {
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function () {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
However, strictly speaking what you're doing is providing labels rather than example values for the inputs, so it would probably be more correct/standards-y to use elements <label> and position them behind the inputs, and then hide them when the inputs are focused/have non-empty values, eg:
HTML:
<p class="row">
<label for="name">Name</label>
<input id="cname" name="name" size="25" class="required noName" value="">
</p>
CSS:
.row {
position: relative;
}
input,
label {
display: block
}
label {
position: absolute;
/*tweak these until label correctly positioned behind input*/
top: 0;
left: 0;
}
input {
background-color: transparent;
}
input:focus,
input.has-value {
background-color: #fff; //hide the label behind the bg color when focused or non-empty
}
jQuery:
//toggle a class depending on whether an input has content or not
input.on('blur', function(){
var $this = $(this);
if ($this.val === "") {
$this.removeClass('has-value');
}
else {
$this.addClass('has-value');
}
});
This second option is more semantic and more accessible too, given that screen reader support for placeholder is patchy

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Categories

Resources