I have a for loop that goes through each input with class="required" , and it its empty it changes its background color. Also, it adds a message to part of the page: "Fields with red background color are required". But, I only want the message to be displayed once. Even if 5 fields are empty, only one message should be displayed. Any suggestions?
Heres my code:
<script type="text/javascript" >
window.onload = function() {
document.getElementById("formID").onsubmit = function() {
var fields = this.getElementsByClassName("validate"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ffb8b8";
var inst = document.getElementById('inst');
var reason = inst.insertRow(-1);
var cell1=reason.insertCell(0);
cell1.innerHTML = '<p>Fields with a red background are required and empty. Please fill them in and try resubmitting. Thanks.</p>';
inst.appendChild(reason);
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
</script>
You could have a flag that gets set to true any time a field fails validation. After the execution of the loop, if the flag is true, append the error message.
Well this should be rather simple - you've already got a boolean variable to say whether the validation has failed - sendForm. So just take the "append message" part out of the loop and into the if.
document.getElementById("formID").onsubmit = function() {
var fields = this.getElementsByClassName("validate"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ffb8b8";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
var inst = document.getElementById('inst');
var reason = inst.insertRow(-1);
var cell1=reason.insertCell(0);
cell1.innerHTML = '<p>Fields with a red background are required and empty. Please fill them in and try resubmitting. Thanks.</p>';
inst.appendChild(reason);
return false;
}
}
Use a flag initialize it to false and once u get any empty field make it true and print the message only if flag is false. Here
<script type="text/javascript" >
window.onload = function() {
document.getElementById("formID").onsubmit = function() {
var fields = this.getElementsByClassName("validate"),
sendForm = true;
var flag=false;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ffb8b8";
if(flag==false) {
var inst = document.getElementById('inst');
var reason = inst.insertRow(-1);
var cell1=reason.insertCell(0);
cell1.innerHTML = '<p>Fields with a red background are required and empty. Please fill them in and try resubmitting. Thanks.</p>';
inst.appendChild(reason);
}
flag=true;
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
</script>
add a boolean flag to indicate that you have already displayed the message
window.onload = function() {
var notified = false;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ffb8b8";
...
if (!notified) {
cell1.innerHTML = '<p>Fields with a red background are required and empty. Please fill them in and try resubmitting. Thanks.</p>';
inst.appendChild(reason);
notified = true;
}
....
}
Related
Trying to add to functions to this form:
validate email (seems to work only when any other JS is commented out)
change color of button when form is filled
Here's my code https://github.com/SallyRagab/WPMU-DEV
// validate email address
var email = document.getElementById('email');
function validateEmail() {
var emailValue = document.getElementById('email').value;
var pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (emailValue.match(pattern)) {
email.classList.remove("is-invalid");
} else {
email.classList.add("is-invalid");
}
}
email.addEventListener('keydown', validateEmail);
// // validate password
var password = document.getElementById('password');
function validatePassword() {
var passwordValue = document.getElementById('password').value;
if (passwordValue.length >= 7) {
password.classList.remove("is-invalid");
} else {
password.classList.add("is-invalid");
}
}
password.addEventListener('keydown', validatePassword);
// Change color of button when form is filled
var inputFields = document.querySelectorAll('input');
function changeColor(){
var button = document.getElementById('button');
var list = [];
for (var i = 0; i < inputFields.length; i++) {
var inputValue = inputFields[i].value;
list.push(inputValue);
}
if (!(list.includes('')) && !(email.classList.contains("is-invalid")) && !(password.classList.contains("is-invalid"))) {
button.classList.add('active-btn');
}
}
for (var i = 0; i < inputFields.length; i++) {
inputFields[i].addEventListener('input', changeColor);}
there's a syntax error.
email.addEventListener('keydown', validation; //missing closing parenthesis
Also when you say:
input.addEventListener('input', changeColor);
I could not find input variable. May you wanted to loop over forms variable and add event listeners to each one of them.
Thank you. I have solved the issue and all functions are working as expected.
// validate email address
var email = document.getElementById('email');
function validateEmail() {
var emailValue = document.getElementById('email').value;
var pattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (emailValue.match(pattern)) {
email.classList.remove("is-invalid");
} else {
email.classList.add("is-invalid");
}
}
email.addEventListener('keydown', validateEmail);
// // validate password
var password = document.getElementById('password');
function validatePassword() {
var passwordValue = document.getElementById('password').value;
if (passwordValue.length >= 7) {
password.classList.remove("is-invalid");
password.classList.add("valid");
} else {
password.classList.add("is-invalid");
password.classList.remove("valid");
}
}
password.addEventListener('keydown', validatePassword);
// Change color of button when form is filled
var inputFields = document.querySelectorAll('input');
function changeColor(){
var button = document.getElementById('button');
var list = [];
for (var i = 0; i < inputFields.length; i++) {
var inputValue = inputFields[i].value;
list.push(inputValue);
}
if (!(list.includes('')) && !(email.classList.contains("is-invalid")) && !(password.classList.contains("is-invalid"))) {
button.classList.add('active-btn');
} else {
button.classList.remove('active-btn');
}
}
for (var i = 0; i < inputFields.length; i++) {
inputFields[i].addEventListener('input', changeColor);}
I created a modal dropdown form with four dropdown lists, with the fourth dropdown containing a link to a document to display once user clicks the submit button. All four dropdowns work fine, however when clicking the submit button the document does not display. The form simply continues to display. Any help is appreciated.
var selectedOptions = {};
$('#link1').on('change', function () {
var a = $(this).val();
selectedOptions['1'] = a;
selectedOptions['2'] = a;
selectedOptions['3'] = a;
if (a !== '') {
for (var i = 0; i < dataSecondSelect[a].length; i++) {
$('#link2').append($("<option></option>")
.attr("value", dataSecondSelect[a][i])
.text(dataSecondSelect[a][i]));
}
}
});
$('#link2').on('change', function () {
var a = $(this).val();
selectedOptions['1'] = a;
selectedOptions['2'] = a;
selectedOptions['3'] = a;
if (a !== '') {
for (var i = 0; i < dataThirdSelect[a].length; i++) {
$('#link3').append($("<option></option>")
.attr("value", dataThirdSelect[a][i])
.text(dataThirdSelect[a][i]));
}
}
});
$('#link3').on('change', function () {
var a = $(this).val();
selectedOptions['1'] = a;
selectedOptions['2'] = a;
selectedOptions['3'] = a;
if (a !== '') {
for (var i = 0; i < dataFourthSelect[a].length; i++) {
$('#link4').append($("<option></option>")
.attr("value", dataFourthSelect[a][i].link)
.text(dataFourthSelect[a][i].form));
}
}
});
$('#clickButton').on('click', function () {
var error = false;
$(".error").remove();
$(".validation-error").removeClass('validation-error');
$('#myModal select').each(function () {
// validate first
if ($(this).val() === "") {
var _message = "Please select an option";
$(this).addClass('validation-error');
$(this).after($('<div class="error"></div>').text(_message));
error=true;
}
});
if (error) { return; }
// form is now validated so get the link
var _index = $("#link4").val();
var _form = dataFourthSelect[_index][0].link;
resetForm($(this)[0]);
$('#myModal').modal('hide');
openDoc(_form);
});
function resetForm(e) {
$(".error").remove();
$(".validation-error").removeClass('validation-error');
e.form.reset();
}
</script>
while going through your given code, i noticed the #link4 does not exists.
so the line var _index = $("#link4").val(); will return undefined which will subsequently fails the following line of code
var _form = dataFourthSelect[_index][0].link;
hope this helps.
I am using this for form validation. I call this function when there is an error and i send it a string as a parameter.
var errList = new Array();
function aerrorList(error){
errList.push(error);
for (var i=0; i < errList.length; i++){
alert(errList[i]);
}
}
here is one of the validation checks:
function lNameValidate() {
var lName = document.getElementById("lastname");
if (lName.value.length < 20 && /^[a-zA-Z0-9- ]*$/.test(lName.value)){
stNumValidate();
} else {
lName.style.border = "red";
errorList("Invalid lName Format");
stNumValidate();
}
}
The current array (using alert) displays the error in a number of popup boxes with only 1 error string each. i want it to display 1 alert which would show all the errors in a list similar to outputting it in a bullet point way.
You can append all the errors to one var and then display it:
function aerrorList(error){
errList.push(error);
var errors = "";
for (var i=0; i < errList.length; i++){
errors += errList[i] + "\n";
}
alert(errors);
}
You could use join method on an array, Here's an example:
errors=['error1','error2','error3']
Here, a is an array of list of your errors, now you can glue them together using whatever you want like this:
error_string=error.join("\n*")
Finally you can make an alert:
alert(error_string)
Try this:
var Errors = {
messages: [],
push: function(message) {
this.messages.push(message);
},
alert: function() {
alert(this.messages.join("\n"));
},
showInElement: function(element) {
element.innerHTML = this.messages.join('<br/>');
},
clear: function() {
this.messages = [];
}
}
var age = 1;
if(age < 18) {
Errors.push("Come back when You 18+");
}
var name = "Jack";
if(name != "John") {
Errors.push("You're not John!");
}
Errors.alert();
var element = document.getElementById('content');
Errors.showInElement(element);
Errors.clear();
<div id="content"></div>
So I ended up using this:
var errList = new Array();
function errorList(error){
errList.push(error);
}
function showErrors() {
alert(errList.join("\n"));
}
where i just call showErrors on the very last validation check if the errList length is > 1 as such:
function emailRestrict() {
var eVal = document.getElementById("email").value;
var atPos = eVal.indexOf("#");
var dotPos = eVal.lastIndexOf(".");
if (atPos < 1 || dotPos < atPos || dotPos >= eVal.length) {
errorList("not valid email");
if (errList.length > 1){
showErrors();
}
return false;
}
else {
if (errList.length > 1){
showErrors();
}
return true;
}
}
I think I am very close here.
I'm trying to iterate through an array and at each iteration, check whether the value is a valid email address.
The problem is, the loop terminates once it hits either a false or a true. How do I iterate through an array without terminating the loop?
validateForm: function() {
var emails = $('#email-addresses').val(),
emailArray = emails.split(',');
for (var i = 0; i < emailArray.length; i++) {
if( ! this.validateEmail(emailArray[i].trim())) {
return false;
}
return true;
};
},
validateEmail: function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
It depends on what you want to do here. If you want to hold a result for every check then look at lincb answer. If you want just a true / false about whether all emails were valid then do:
validateForm: function() {
var emails = $('#email-addresses').val(),
emailArray = emails.split(',');
var isValid = true;
for (var i = 0; i < emailArray.length && isValid == true; i++) {
if( ! this.validateEmail(emailArray[i].trim())) {
isValid = false;
}
};
return isValid;
},
In Javascript, return will end the function regardless of any loops. Here is a possible fix:
validateForm: function() {
var emails = $('#email-addresses').val(),
emailArray = emails.split(',');
var returns = new Array();
for (var i = 0; i < emailArray.length; i++) {
if( ! this.validateEmail(emailArray[i].trim())) {
returns[i] = false;
}
returns[i] = true;
}
return returns;
},
Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}
First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.
It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.
make sure the type attribute in tag is "text/javascript" not "script/javascript".
I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.