Javascript: registration form help required - javascript

I'm a rookie scripter and what I'm trying to do is: create a registration form and a calculator. If you enter a password less than 5 symbols or a username less than 3 symbols you will not be able to continue. But even if I enter an username with more than 3 symbols and a password with more than 5 symbols it still displays the error message.
The code: http://pastebin.com/KqYbDJMw
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){
if (pw.length < 5 && user.length < 3){
alert("An error occured");
}
else {
alert("Thank you for registering to my website.");
var action = prompt("Welcome to my calculator. For addition press 1, for substraction press 2, for multiplication press 3, for division press 4 and for square root press 5:", "");
var firstNum = new Array();
var secondNum = new Array();
var result = new Array();

You want to fail if either of those conditions are true, so use || (or) instead of && (and)
if (pw.length < 5 && user.length < 3)
should be
if (pw.length < 5 || user.length < 3)
Also, you want to fetch the current values each time you do your check, so this
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
should be inside your function. Ie
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;

The problem is you get :
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){...
on load. So it will always be blank. To get it at the time the user clicks 'continue..' move it inside the function like so:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
...

You are not too far off. The two main changes are you need to put your variable assignment inside of the function you are calling so it can get the values when the submit button is pressed.
Also you probably want to use an Or instead when validating the fields. Here is an example:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
if (pw.length < 5 || user.length < 3){
alert("An error occured");
}
If you're doing any kind of validation, there are some great jQuery libraries that make it look great and are easy to implement. You might want to to a quick google search.

Related

Why is my computer generated code undefined?

In JavaScript I am making a random password generator, where the user can choose the size (8 to 128 characters) and four parameters (if they want to include: numbers, capital and/or lowercase letters, and special characters).
I have made a large empty array where true responses to the parameters are then pushed into it, and following, the computer uses the large array to create a random password from the options.
// for loop
// sizeOfPassword = sizeOfPassword;
for (i = 0; i < sizeOfPassword; i++) {
var index = Math.floor.parseInt(Math.random() * allOptions.length);
var computerChoice = allOptions[index];
passwordElement.text = passwordString
var passwordString = password.join("");
var passwordElement = document.querySelector("password")
randomPassword += computerChoice;
var password = []
// var = 0
for (; i < sizeOfPassword - 1; i++) {
password.push(randomCharacter)
console.log(passwordString);
console.log(passwordElement.text);
passwordElement.text = passwordString
}
}
// Assignment Code
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = getPasswordInfo();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
Below is the second half of my code, but each time I test it in my browser, the computer's generated password returns as undefined.
How and where in my code can I properly assign the value of my computer generated string?
This getPasswordInfo is returning nothing.
var password = getPasswordInfo();
Try to return passwordString but difficult to tell, the code looks partial, the function getPasswordInfo is not defined in the question.

Cant get indexOf statement to work

Ultimately I am prompting the user for a guess, which is then ultimately changed so regardless of what the user inputs it will always Capitalize the first letter and make the rest lowercase. (Im doing this so if the user types in a guess the string will either match or not match the values in an array.) I tried doing a for statement to use a loops counter (3 total guesses is what im looking for). But when I try to use a indexOf to check the array, I keep getting an "unexpected token" error on that line that contains the indexOf statement. So the question would be (1) what am i doing wrong in this line of code?
//declare variables
var sportsArray = new Array("Football", "Basketball", "Rollerblading", "Hiking", "Biking", "Swimming");
var name = prompt("Enter your name");
var loops = 0;
var score = 0;
var sGuess = prompt("enter your sport guess");
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
var usableGuess = sFirstCap + sSecondLow;
while(loops < 4){
if(sportsArray.indexOf(usableGuess) = 0 {
document.write("nice guess");
loops++;
}else {
document.write("loser");
loops++;
}
}
This works for checking the whole array:
var sportsArray = new Array("Football", "Basketball", "Rollerblading", "Hiking", "Biking", "Swimming");
var name = prompt("Enter your name");
var loops = 0;
var score = 0;
var sGuess = prompt("enter your sport guess");
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
var usableGuess = sFirstCap + sSecondLow;
while(loops < 4){
if(sportsArray.indexOf(usableGuess) > -1) {
document.write("nice guess");
loops++;
}else {
document.write("loser");
loops++;
}
}
You'd want to use indexOf(guess) > -1 to check if the guess is present at any index of the array. For checking just one index position it would be indexOf(guess) == 0.
sportsArray.indexOf(usableGuess) === 0) instead of sportsArray.indexOf(usableGuess) = 0
It's a good practice to check for equality with constant on the left side. It will throw an exception in most browsers:
var a = 3;
if (12 = a) { // throws ReferenceError: invalid assignment left-hand side in Firefox
//do something
}
Also: use tools that provide static code analysis. A jslint.com or jshint.com for js is a good choice. There are also IDE plugins explicitely for that (using either of those two and more), see Is there a working JSLint Eclipse plug-in?.

jQuery - If this or this get failed inputs name

I'm trying to get the name of the of the input that failed this tiny validation like so:
var username = jQuery("#modlgn-username").val();
var password = jQuery("#modlgn-passwd").val();
if(username < 2 || password < 2){
jQuery('.login-error').html('Incorrect'+jQuery(this).attr("name")).slideDown(300);
}else{
sendLogin(datasubmit);
}
But I am so far I've been very unsuccessful. Is this at all possible?
UPDATE:
Sorry my question seems to be unclear, I know how to validate the fields that parts fine.. I am struggling with:
jQuery(this).attr("name");
It does not return the failed inputs name. How would i get the failed inputs name?
As per comment
I'm just trying to check that the two fields are at least more then 2chars.
You need to use length property
if(username.length < 2 || password.length < 2){
jQuery('.login-error').html('Incorrect'+jQuery(this).attr("name")).slideDown(300);
}else{
sendLogin(datasubmit);
}
EDIT
It is very difficult to analyse this in the code fragment jQuery(this).attr("name"); without seeing complete code.
You can this, As per comment given below
var username = jQuery("#modlgn-username").val();
var password = jQuery("#modlgn-passwd").val();
if(username < 2 ){
jQuery('.login-error').html('Incorrect' + jQuery("#modlgn-username").attr("name")).slideDown(300);
}else if(password < 2){
jQuery('.login-error').html('Incorrect' + jQuery("#modlgn-passwd").attr("name")).slideDown(300);
}
else{
sendLogin(datasubmit);
}
Can you try this, Assumed you want to validate input length.
var username = jQuery("#modlgn-username").val();
var password = jQuery("#modlgn-passwd").val();
if(username.length < 2 || password.length < 2){
jQuery('.login-error').html('Incorrect'+jQuery(this).attr("name")).slideDown(300);
return false;
}else{
sendLogin(datasubmit);
}

Qualtrics Javascript questions - Matrix Tables

I'm having some issues in Qualtrics with certain functions that are easy enough in a single question, but become impossible when using a Matrix Table or a Side-by-Side.
1) Content validation for individual fields in the Matrix Table - currency in the Matrix table, you can only check validation for multiple fields and generate a single error.
2) Required Response for a field based on an entry in the previous field in that row of the Matrix Table
3) Recode Values of text entries in a Matrix Table - there doesn't seem to be a way to this in a Matrix Table. Again, it's very simple to do with a single question.
Basically, I'd like a user to be able to complete only a single row of the Matrix Table if they want, but for the rows they complete, I need to validate specific fields and require response for specific fields, and possibly re-code their text entries.
Is there an easy way to do this with Javascript instead?
Thanks...
My guess is that JavaScript will take care of it. I've had to write several scripts because the validation features in Qualtrics are limited, to say the least.
Depending on how your Qualtrics validations options are set up you'll probably have to use functions from Qualtrics' JavaScript. Below is the basic structure you would use. Not really knowing anything about your Qualtrics question ids, I used placeholders.
Update: I would recommend using the side-by-side question type.
Here's a
link to the question/survey
To get you started off, here is the code for the first student. You need to copy the same pattern for students 2-5. You can go so many ways with validation style (in-line messages, pop-ups) that I didn't even go there. The email validation you can choose in Qualtrics under content validation for the two email columns. You can also choose phone number validation as well. The validation here will just prevent a user from going to the next page until they meet all the criteria. You could explain the validation criteria in the body of the question.
The questions ids I used are listed first and correspond exactly to the placement of the items in the screen shot except for the Y/N question which is different for a side-by-side question and has the id QR~QID9#5~1~1 for yes and QR~QID9#5~1~2 for no. I don't know what your skills are regarding Firebug but you will need to find the ids that pertain to your specific questions and replace the ones below with them.
I would also recommend using Embedded Data variables to feed in the answers so that you have nice clean legible data in your download. From what I remember, the structure of Qualtrics matrix and side-by-side data are not very usable.
Hopefully, this makes sense to you. If not, ask. I know from personal experience how frustrating it is to find javascript support for Qualtrics.
Qualtrics.SurveyEngine.addOnload(function () {
/*Place Your Javascript Below This Line*/
//QR~QID9#1~1~1~TEXT - QR~QID9#2~1~1~TEXT - QR~QID9#3~1~1~TEXT - QR~QID9#4~1~1~TEXT - QR~QID9#5~1~1/QR~QID9#5~1~2 - QR~QID9#6~1~1~TEXT
//QR~QID9#1~2~1~TEXT - QR~QID9#2~2~1~TEXT - QR~QID9#3~2~1~TEXT - QR~QID9#4~2~1~TEXT - QR~QID9#5~2~1/QR~QID9#5~2~2 - QR~QID9#6~2~1~TEXT
//QR~QID9#1~3~1~TEXT - QR~QID9#2~3~1~TEXT - QR~QID9#3~3~1~TEXT - QR~QID9#4~3~1~TEXT - QR~QID9#5~3~1/QR~QID9#5~3~2 - QR~QID9#6~3~1~TEXT
//QR~QID9#1~4~1~TEXT - QR~QID9#2~4~1~TEXT - QR~QID9#3~4~1~TEXT - QR~QID9#4~4~1~TEXT - QR~QID9#5~4~1/QR~QID9#5~4~2 - QR~QID9#6~4~1~TEXT
//QR~QID9#1~5~1~TEXT - QR~QID9#2~5~1~TEXT - QR~QID9#3~5~1~TEXT - QR~QID9#4~5~1~TEXT - QR~QID9#5~5~1/QR~QID9#5~5~2 - QR~QID9#6~5~1~TEXT
var notvalidphbook1 = 0, notvalidphbook2 = 0, notvalidphbook3 = 0, notvalidphbook4 = 0, notvalidphbook5 = 0;
var phsbooks; //gets sum of notvalidphbook items
var bookrecode1, bookrecode2, bookrecode3, bookrecode4, bookrecode5;
var notvalidemail1 = 0, notvalidemail2 = 0, notvalidemail3 = 0, notvalidemail4 = 0, notvalidemail5 = 0;
var emails; //gets sum of notvalidemail items
var validates; //validation variable that decides if user proceeds or not
Qualtrics.SurveyPage.Question.prototype.validate = function (element) {
//Student name entered
var student1y = $('QR~QID9#1~1~1~TEXT').getValue();
var student2y = $('QR~QID9#1~2~1~TEXT').getValue();
var student3y = $('QR~QID9#1~3~1~TEXT').getValue();
var student4y = $('QR~QID9#1~4~1~TEXT').getValue();
var student5y = $('QR~QID9#1~5~1~TEXT').getValue();
//Student phone number
var student1phone = $('QR~QID9#2~1~1~TEXT').getValue();
var student2phone = $('QR~QID9#2~2~1~TEXT').getValue();
var student3phone = $('QR~QID9#2~3~1~TEXT').getValue();
var student4phone = $('QR~QID9#2~4~1~TEXT').getValue();
var student5phone = $('QR~QID9#2~5~1~TEXT').getValue();
//Emails match
var student1emailA = $('QR~QID9#3~1~1~TEXT').getValue();
var student1emailB = $('QR~QID9#4~1~1~TEXT').getValue();
var student2emailA = $('QR~QID9#3~2~1~TEXT').getValue();
var student2emailB = $('QR~QID9#4~2~1~TEXT').getValue();
var student3emailA = $('QR~QID9#3~3~1~TEXT').getValue();
var student3emailB = $('QR~QID9#4~3~1~TEXT').getValue();
var student4emailA = $('QR~QID9#3~4~1~TEXT').getValue();
var student4emailB = $('QR~QID9#4~4~1~TEXT').getValue();
var student5emailA = $('QR~QID9#3~5~1~TEXT').getValue();
var student6emailB = $('QR~QID9#4~5~1~TEXT').getValue();
//Student book needs
var student1booky = $('QR~QID9#5~1~1').getValue();
var student1bookn = $('QR~QID9#5~1~2').getValue();
var student2booky = $('QR~QID9#5~2~1').getValue();
var student2bookn = $('QR~QID9#5~2~2').getValue();
var student3booky = $('QR~QID9#5~3~1').getValue();
var student3bookn = $('QR~QID9#5~3~2').getValue();
var student4booky = $('QR~QID9#5~4~1').getValue();
var student4bookn = $('QR~QID9#5~4~2').getValue();
var student5booky = $('QR~QID9#5~5~1').getValue();
var student6bookn = $('QR~QID9#5~5~2').getValue();
//Student book name
var student1bookname = $('QR~QID9#6~1~1~TEXT').getValue();
var student2bookname = $('QR~QID9#6~2~1~TEXT').getValue();
var student3bookname = $('QR~QID9#6~3~1~TEXT').getValue();
var student4bookname = $('QR~QID9#6~4~1~TEXT').getValue();
var student5bookname = $('QR~QID9#6~5~1~TEXT').getValue();
if (student1y == '') {
//alert("no name provided, no other info needed");
//"no name provided, no other info needed"
} else if (student1y != '' && (student1phone == '' || (student1emailA == '' || student1emailB == '') || (student1booky == null && student1bookn == null))) {
//alert("you need to provide a phone number and enter the student's book needs");
notvalidphbook1 = 1;
}
else if (student1y != '' && (student1phone != '' && (student1emailA != '' && student1emailB != '') && (student1booky == null && student1bookn == null))) {
notvalidphbook1 = 0;
else {
//alert("thank you for providing a phone number and specifying book needs");
if (student1booky == 'QR~QID9#5~1~1') {
bookrecode1 = 'Y';
} else {
bookrecode1 = 'N';
}
}
if (student1emailA == '' && student1emailB == '') {
//alert("no email provided, no match needed");
//"no email provided, no match needed"
} else if (student1emailA != '' && student1emailA == student1emailB) {
//alert("the emails match");
//"the emails match"
notvalidemail1 = 0;
} else {
//alert("the emails don't match");
//"the emails don't match"
notvalidemail1 = 1;
}
Qualtrics.SurveyEngine.setEmbeddedData('Student1Name', student1y);
Qualtrics.SurveyEngine.setEmbeddedData('Student1Phone', student1phone);
Qualtrics.SurveyEngine.setEmbeddedData('Student1Email', student1emailA);
Qualtrics.SurveyEngine.setEmbeddedData('Student1Txt', bookrecode1);
Qualtrics.SurveyEngine.setEmbeddedData('Student1TxtName', student1bookname);
phsbooks = notvalidphbook1 + notvalidphbook2 + notvalidphbook3 + notvalidphbook4 + notvalidphbook5;
emails = notvalidemail1 + notvalidemail2 + notvalidemail3 + notvalidemail4 + notvalidemail5;
validates = phsbooks + emails;
if (validates == 0) { //validates only if the sum is equal to zero
return true; //this let's the user continue
} else {
return false; //this prevents the user from proceeding to the next page
}
}
});

Code won't run due to string length issue

Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()
This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.
Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.

Categories