Javascript code broken - javascript

This is my first attempt at a little more complex code structure. The thing is my IDE says it technically works , jsfiddle says it doesn't, it actually initializes only the two confirm functions that I declared "confirmUserName();" and "confirmFullName();"
Can someone explain why i did such a horrible job.
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList); v
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if(list.length == 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if(list[i] == undefined) {
list[i] = usrName;
return list;
} else if(i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery; /
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm == true) {
return startRide;
} else {
return fullnameQuery;
}
}
if(username == undefined) {
usernameQuery = function() {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function() {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if(fullname == undefined) {
fullnameQuery = function() {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function() {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();

There is a lot wrong with the code you posted -- I'll just take one chunk:
function confirmUserName() {
// The return value of `confirm` is ignored.
confirm("Is " + username + " your first choice?");
// confirmUserName is the name of your function.
// You sould be using `===` instead of `==`
// Or, not comparing against true at all.
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
Fixed function:
function confirmUserName() {
var res = confirm("Is " + username + " your first choice?");
if (res) {
return fullnameQuery;
} else {
return usernameQuery;
}
}

It does not throw Errors with this, but I dont know in which situation you want your code to be implemented and what it should do, I hope this is what you need:
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList);
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if (list.length === 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if (list[i] === undefined) {
list[i] = usrName;
return list;
} else if (i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName === true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery;
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm === true) {
return startRide;
} else {
return fullnameQuery;
}
}
if (username === undefined) {
usernameQuery = function () {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function () {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if (fullname === undefined) {
fullnameQuery = function () {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function () {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();

Related

How can I stop this from writing a value to all dictionaries? (Javascript)

Intro
So I have stumbled across this problem yesterday, and I've been stumped trying to figure this out myself. I only have this problem with JavaScript.
Problem
I've been creating a programming language with JS since the start of this week, and I was enjoying myself the entire week making it. The problem here is that when I carry dictionaries across functions, it has some problems reading and writing into those dictionaries. When I check the console logs, I see that not just the dictionary in the function was written, but all of the instances of that dictionary were written.
Code
Here is the code to graph.js:
function codeToArray(code) {
let codeArray = {commands:[], vars:{x:{value:0, read_only:true},y:{value:0, read_only:false}}};
let commands = code.split("\n");
for (i = 0; i < commands.length; i++) {
let command = commands[i];
let inputs = command.split(" ");
if (inputs[0].toLowerCase() !== ";") {
// Arithmetics
if (inputs[0].toLowerCase() === "+") { // Addition
codeArray.commands.push({name:"add", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "-") { // Subtraction
codeArray.commands.push({name:"subtract", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "*") { // Multiplication
codeArray.commands.push({name:"multiply", variable:inputs[1], value:inputs[2], syntax_id:1});
} else if (inputs[0].toLowerCase() === "/") { // Division
codeArray.commands.push({name:"divide", variable:inputs[1], value:inputs[2], syntax_id:1});
}
// I/O
else if (inputs[0].toLowerCase() === ":") { // Set
codeArray.commands.push({name:"set", variable:inputs[1], value:inputs[2], syntax_id:1});
}
// Conditional Statements
else if (inputs[0].toLowerCase() === "if") { // If Statement
let ifCommand = "";
for (j = 4; j < inputs.length; j++) {
if (j > 4) {
ifCommand += " " + inputs[j];
} else {
ifCommand += inputs[j];
}
}
let ifCommandArray = codeToArray(ifCommand).commands[0];
codeArray.commands.push({name:"if", value1:inputs[1], condition:inputs[2], value2:inputs[3], command:ifCommandArray, syntax_id:2});
}
}
}
return codeArray
}
function parseValue(value, variables) {
let return_value = value;
console.log(value);
console.log(variables);
if (value.charAt(0) === "$") {
let variable_name = return_value.substring(1, value.length);
console.log(variable_name);
let variable = variables[variable_name];
console.log(variable);
if (variable === undefined) {
return_value = NaN;
} else {
return_value = variable.value;
}
} else {
return_value = parseFloat(value);
}
console.log(return_value);
return return_value
}
function runCodeArray(commands, variables) {
for (i = 0; i < commands.length; i++) {
let command = commands[i];
if (command.syntax_id === 1) { // Simple Syntax (Variable Value Syntax)
if (command.name === "add") { // Addition
let variable = variables[command.variable];
if (variable === undefined) {
let error_message = `Variable cannot be found (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
if (variable.read_only === true) {
let error_message = `A read-only variable was trying to be written (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
let value = parseValue(command.value, variables);
if (value === NaN) {
let error_message = `The value parameter is invalid (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
variable.value += value;
} else if (command.name === "set") { // Set
let variable = variables[command.variable];
if (variable === undefined) {
variables[command.variable] = {value:0, read_only:false};
variable = variables[command.variable];
}
if (variable.read_only === true) {
let error_message = `A read-only variable was trying to be written (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
let value = parseValue(command.value, variables);
if (value === NaN) {
let error_message = `The value parameter is invalid (line ${i+1} ignoring comments)`;
return {commands:commands, variables:variables, return_message:error_message};
}
variable.value = value;
}
}
}
return {commands:commands, variables:variables, return_message:true};
}
var url_string = ...graph.html?pattern=%3A+a+42%0D%0A%3A+b+%24a%0D%0A%3A+c+%24b%0D%0A // window.location.href;
var url = new URL(url_string);
var pattern = url.searchParams.get("pattern");
let codeArray = codeToArray(pattern);
// console.log(codeArray);
let codeArrayOut = runCodeArray(codeArray.commands, codeArray.vars); // Will return true in return_message if everything is good, and will return a string in return_message if an error occurs.
// console.log(codeArrayOut);
if (codeArrayOut.return_message !== true) {
alert("Error: " + codeArrayOut.return_message);
}
Sorry if the code is too long, boring or messy for you to read. Here is the function that's causing the most problems:
function parseValue(value, variables) {
let return_value = value;
console.log(value);
console.log(variables);
if (value.charAt(0) === "$") {
let variable_name = return_value.substring(1, value.length);
console.log(variable_name);
let variable = variables[variable_name];
console.log(variable);
if (variable === undefined) {
return_value = NaN;
} else {
return_value = variable.value;
}
} else {
return_value = parseFloat(value);
}
console.log(return_value);
return return_value
}
Outro
I'm still learning in JavaScript, so I hope that you can solve this problem (because I can't).

Undefined JS password generator

I'm making a simple password generator that prompts the user for conditions for a password such as case, symbols, and numbers then generates a password on click.
I have set up functions to handle these, however, cannot get the password to actually generate.
I'm getting an error where the password that's generated is undefined?
//Password option input
const resultEl = document.getElementById("result");
var characters = prompt("How many characters should the password containt (8-128)");
var upperCase = prompt("Should the password contain uppercase Letters?");
var lowerCase = prompt("Should the password contain lowercase Letters");
var numbers = prompt("Should the password contain numbers?");
var symbols = prompt("Should the password contain symbols?");
var generateEl = document.getElementById("generate");
function randomFunc(input) {
if (input === "hasUpper") {
console.log("upper");
return getRandomUpper();
}
if (input === "hasLower") {
getRandomLower();
console.log("lower")
}
if (input === "hasNumbers") {
getRandomNumber();
console.log("numbers")
}
if (input === "hasSymbols") {
getRandomSymbol();
console.log("symbols")
}
}
if (characters > 7 && characters < 129) {
var length = parseInt(characters, 10);
console.log("length: " + length);
} else {
var length = false;
alert("Invalid Password length");
}
// if input is "yes" return true
if (upperCase.toLowerCase() === 'yes') {
var hasUpper = true;
console.log("upper: " + hasUpper);
}
if (lowerCase.toLowerCase() === 'yes') {
var hasLower = true;
console.log("lower: " + hasLower);
}
if (numbers.toLowerCase() === 'yes') {
var hasNumbers = true;
console.log("number: " + hasNumbers);
}
if (symbols.toLowerCase() === 'yes') {
var hasSymbols = true;
console.log("symbol: " + hasSymbols);
}
generateEl.addEventListener('click', function() {
resultEl.innerText = generatePassword(hasUpper, hasLower, hasNumbers, hasSymbols, length);
console.log("generatebut");
});
//Generate password function
function generatePassword(hasUpper, hasLower, hasNumbers, hasSymbols, length) {
//1. initialise password variable
let generatedPassword = '';
const typesCount = hasUpper + hasLower + hasNumbers + hasSymbols;
//console.log('typesCount ', typesCount);
const typesArr = [{
hasUpper
}, {
hasLower
}, {
hasNumbers
}, {
hasSymbols
}]
//3. loop over length call generator function for each type
for (let i = 0; i < length; i += typesCount) {
typesArr.forEach(function(type) {
const funcName = Object.keys(type)[0];
console.log('funcNames ', funcName);
generatedPassword = randomFunc(funcName);
});
}
//4. Add final password to password variable and return
const finalPassword = generatedPassword;
console.log("password: " + generatedPassword);
return finalPassword;
}
// Password generator functions
function getRandomLower() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
function getRandomUpper() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}
function getRandomNumber() {
return String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}
function getRandomSymbol() {
const symbols = "!##$%^&*()<>?,."
return symbols[Math.floor(Math.random() * symbols.length)];
}
<main class="container">
<header>
<h1 class="title">Password Generator</h1>
</header>
<section class="generator-box">
<h2 class="sub-title">Generate a Password</h2>
<div class="pass-div pass-hold">
<h3>Your secure Password</h3>
<span id="result"></span>
</div>
<section class="button-div">
<button href="#" class="button" id="generate">Generate</button>
</section>
</section>
</main>
The randomFunc function is only returning a character for the "hasUpper" condition. You need to explicitly return a character regardless of case like so:
function randomFunc(input) {
let randomChar;
if (input === "hasUpper") {
randomChar = getRandomUpper();
}
if (input === "hasLower") {
randomChar = getRandomLower();
}
if (input === "hasNumbers") {
randomChar = getRandomNumber();
}
if (input === "hasSymbols") {
randomChar = getRandomSymbol();
}
return randomChar;
}
The generatePassword function is overwriting the generatedPassword variable on every loop. So even if you were returning characters from randomFunc your final password would only ever be 1 character. I modified that and removed the redundant finalPassword variable like so:
function generatePassword(hasUpper, hasLower, hasNumbers, hasSymbols, length) {
let generatedPassword = '';
const typesCount = hasUpper + hasLower + hasNumbers + hasSymbols;
const typesArr = [{ hasUpper }, { hasLower }, { hasNumbers }, { hasSymbols }]
for (let i = 0; i < length; i += typesCount) {
typesArr.forEach(function(type) {
const funcName = Object.keys(type)[0];
generatedPassword = generatedPassword + randomFunc(funcName);
});
}
return generatedPassword;
}

How to delete object in array using localstorage?

I have to delete object in array and it should be deleted from localstorage. I am trying to delete it by using splice method but not actually getting how to use it.
Folloeing is my code which i have tried-
var details = [];
function addEntry() {
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
var srno = document.getElementById("txtpid").value;
var name = document.getElementById("txtpname").value;
var dob = document.getElementById("txtpdob").value;
var email = document.getElementById("txtpemail").value;
var address = document.getElementById("txtpaddr").value;
var contact = document.getElementById("txtpmobile").value;
var obbbj = {
txtpid: srno,
txtpname: name,
txtpdob: dob,
txtpemail: email,
txtpaddr: address,
txtpmobile: contact
};
localStorage.setItem("details", JSON.stringify(obbbj));
existingEntries.push(obbbj);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
showEntry();
console.log(existingEntries);
//location.reload();
}
function showEntry() {
var messageBox = document.getElementById("display");
messageBox.value = "";
document.getElementById("txtpid").value = "";
document.getElementById("txtpname").value = "";
document.getElementById("txtpdob").value = "";
document.getElementById("txtpemail").value = "";
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpmobile").value = "";
var render = "<table border='1'>";
render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";
var allEntriesoo = {};
var detailsOOO = {};
for (i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var person = localStorage.getItem(key);
if (key == 'allEntries')
allEntriesoo = JSON.parse(person);
if (key == 'details')
detailsOOO = JSON.parse(person);
var data = JSON.parse(person);
}
for (var key in allEntriesoo) {
console.error(allEntriesoo[key])
render += "<tr><td>" + allEntriesoo[key].txtpid + "</td><td>" + allEntriesoo[key].txtpname + " </td>";
render += "<td>" + allEntriesoo[key].txtpdob + "</td>";
render += "<td>" + allEntriesoo[key].txtpemail + "</td>";
render += "<td>" + allEntriesoo[key].txtpaddr + "</td>";
render += "<td>" + allEntriesoo[key].txtpmobile + "</td>";
render += "<td><input type='button' value='Delete' onClick='return deleteEntry(" + i + ")'></td>";
render += "<td><input type='button' value='Edit' onClick='return editInfo(" + i + ")'></td></tr>";
}
render += "</table>";
display.innerHTML = render;
}
function nameVal() {
document.getElementById("txtpname").focus();
var n = document.getElementById("txtpname").value;
var r;
var letters = /^[a-zA-Z]+$/;
if (n == null || n == "") {
alert("please enter user name");
return null;
n.focus();
} else {
if (n.match(letters) && n != "") {
r = ValidateEmail();
return r;
} else {
alert("please enter alphabates");
document.getElementById("txtpname").value = "";
document.getElementById("txtpname").focus();
return null;
}
}
}
function ValidateEmail() {
var uemail = document.getElementById("txtpemail").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
document.getElementById("txtpemail").value = "";
document.getElementById("txtpemail").focus();
return null;
}
}
function alphanumeric() {
var uadd = document.getElementById("txtpaddr").value;
var letters = /^[0-9a-zA-Z]+$/;
if (uadd == null || uadd == "") {
alert("plz enter address");
uadd.focus();
} else {
if (uadd.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpaddr").focus();
return false;
}
}
}
function cntVal() {
var n = document.getElementById("txtpmobile").value;
var r1;
var letters = /^\d{10}$/;
if (n !== null || n !== "") {
if (n.match(letters)) {
r1 = alphanumeric();
return r1;
} else {
alert("please enter contact number");
document.getElementById("txtpmobile").value = "";
document.getElementById("txtpmobile").focus();
return null;
}
} else {
alert("please enter contact Number");
return null;
n.focus();
}
}
function deleteEntry(id) {
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') JSON.parse(localStorage.getItem('allEntries')): [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index = i;
break;
}
}
if (index === undefined) return
entry.splice(index, 1);
localStorage.setItem('entry', JSON.stringify(entry));
}
function clearstorage() {
localStorage.clear();
window.location.reload();
}
window.onload = function() {
showEntry();
};
In your deleteEntry function you are setting a new item in localStorage called 'entry'. So you are not setting 'allEntries' and thats probably why its showing up like that, 'allEntries' has not been updated. So just set all entries again. localStorage.setItem('allEntries', JSON.stringify(entry));
You are also missing the '?' for you variable 'entry'...
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; <-- it should look like this.
Its the same as an 'if else statement'
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index=i;
break;
}
}
if(index === undefined) return
entry.splice(index, 1);
localStorage.setItem('allEntries', JSON.stringify(entry)); <--- like this
}
You can use create a temporary object and then replace it in localStorage.
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = JSON.parse(localStorage.getItem('allEntries'));
var temp= [];
for (var i = 0; i < entry.length; i++) {
if (entry[i].id !== id) {
temp.push(entry[i]);
}
}
localStorage.setItem('entry', JSON.stringify(temp));
}

Validate form function jump to error?

I have a form with a validation script that works perfectly. I would however like the form to jump to the fields that doesn't validate or display the name of the fields in the error message.
The code I use to validate is:
else
{
var valid = document.formvalidator.isValid(f);
}
if (flag == 0 || valid == true) {
f.check.value = '<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('There was an error with the fields..');
return false;
}
return true;
How can I get the alert to name the fields that need to be filled in correctly or jump to the specific field?
Edited ----------
Hi,
Thanks for help so far. I'm very new to JS. The form is in a component of Joomla.
The full function that validates the form is
function validateForm(f){
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){
var flag = 0;
for (var i=0;i < f.elements.length; i++) {
el = f.elements[i];
if ($(el).hasClass('required')) {
var idz= $(el).getProperty('id');
if(document.getElementById(idz)){
if (!document.getElementById(idz).value) {
document.formvalidator.handleResponse(false, el);
flag = flag + 1;
}
}
}
}
}
else {
var valid = document.formvalidator.isValid(f);
}
if(flag == 0 || valid == true){
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('<?php echo JText::_('JBJOBS_FIEDS_HIGHLIGHTED_RED_COMPULSORY'); ?>');
return false;
}
return true;
}
External js file:
var JFormValidator = new Class(
{
initialize : function() {
this.handlers = Object();
this.custom = Object();
this.setHandler("username", function(b) {
regex = new RegExp("[<|>|\"|'|%|;|(|)|&]", "i");
return !regex.test(b)
});
this.setHandler("password", function(b) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(b)
});
this.setHandler('passverify',
function (value) {
return ($('password').value == value);
}
); // added March 2011
this.setHandler("numeric", function(b) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(b)
});
this
.setHandler(
"email",
function(b) {
regex = /^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(b)
});
var a = $$("form.form-validate");
a.each(function(b) {
this.attachToForm(b)
}, this)
},
setHandler : function(b, c, a) {
a = (a == "") ? true : a;
this.handlers[b] = {
enabled : a,
exec : c
}
},
attachToForm : function(a) {
a.getElements("input,textarea,select")
.each(
function(b) {
if (($(b).get("tag") == "input" || $(b)
.get("tag") == "button")
&& $(b).get("type") == "submit") {
if (b.hasClass("validate")) {
b.onclick = function() {
return document.formvalidator
.isValid(this.form)
}
}
} else {
b.addEvent("blur", function() {
return document.formvalidator
.validate(this)
})
}
})
},
validate : function(c) {
c = $(c);
if (c.get("disabled")) {
this.handleResponse(true, c);
return true
}
if (c.hasClass("required")) {
if (c.get("tag") == "fieldset"
&& (c.hasClass("radio") || c.hasClass("checkboxes"))) {
for ( var a = 0;; a++) {
if (document.id(c.get("id") + a)) {
if (document.id(c.get("id") + a).checked) {
break
}
} else {
this.handleResponse(false, c);
return false
}
}
} else {
if (!(c.get("value"))) {
this.handleResponse(false, c);
return false
}
}
}
var b = (c.className && c.className
.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? c.className
.match(/validate-([a-zA-Z0-9\_\-]+)/)[1]
: "";
if (b == "") {
this.handleResponse(true, c);
return true
}
if ((b) && (b != "none") && (this.handlers[b])
&& c.get("value")) {
if (this.handlers[b].exec(c.get("value")) != true) {
this.handleResponse(false, c);
return false
}
}
this.handleResponse(true, c);
return true
},
isValid : function(c) {
var b = true;
var d = c.getElements("fieldset").concat($A(c.elements));
for ( var a = 0; a < d.length; a++) {
if (this.validate(d[a]) == false) {
b = false
}
}
new Hash(this.custom).each(function(e) {
if (e.exec() != true) {
b = false
}
});
return b
},
handleResponse : function(b, a) {
if (!(a.labelref)) {
var c = $$("label");
c.each(function(d) {
if (d.get("for") == a.get("id")) {
a.labelref = d
}
})
}
if (b == false) {
a.addClass("invalid");
a.set("aria-invalid", "true");
if (a.labelref) {
document.id(a.labelref).addClass("invalid");
document.id(a.labelref).set("aria-invalid", "true");
}
} else {
a.removeClass("invalid");
a.set("aria-invalid", "false");
if (a.labelref) {
document.id(a.labelref).removeClass("invalid");
document.id(a.labelref).set("aria-invalid", "false");
}
}
}
});
document.formvalidator = null;
window.addEvent("domready", function() {
document.formvalidator = new JFormValidator()
});
Where would I edit the code as some of you have answered below?
with jquery js library, scroll to element (id selector or class)
<p class="error">There was a problem with this element.</p>
This gets passed to the ScrollTo plugin in the following way.
$.scrollTo($('p.error:1'));
see source
Using jQuery's .each, loop over the fields. On every iteration the item that is being invesitigated will be under the this variable.
Therefore, this.id gives the id of the element you're looking for. Store these to collect all the incorrect fields, then highlight them or print their names in a message.
Keep in mind, this is the basic idea, I cannot give an actual answer until you show the code that handles the form.
Kind regards,
D.
You can have your isValid routine return the error message instead of returning a boolean.
In isValid, you can build up the error message to include the field names with errors.
Instead of checking "valid == true", you will check "errorMessage.length == 0".
If you want to focus on an error field (you can only focus on one), then do that in the isValid routine as well.
function isValid(f) {
var errorMessage = "";
var errorFields = "";
var isFocused = false;
...
if (field has an error) {
errorFields += " " + field.name;
if (!isFocused) {
field.focus();
isFocused = true;
}
}
...
if (errorFields.length > 0) {
errorMessage = "Errors in fields: " + errorFields;
}
return (errorMessage);
}
then, in your calling routine:
var errorMessage = isValid(f);
if (flag == 0 || errorMessage.length == 0) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert(errorMessage);
return false;
}
return true;

Null error is coming document.getElementByid("dthchannel" + [i] is null)

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;
You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Categories

Resources