Javascript multiple alerts for multiple fields - javascript

I’m working on a function where I’m gonna check numerous input fields with regexes. However, instead of letting it return false for each of the ”ifs” I’d like it to go through all of the conditions, and then output all of the innerHTMLs at once, from different conditions and input boxes. The text appears under each of the boxes. To give you a hint of what I'm going for.
Instead of having to input something to one box, for getting an error - correcting it, then getting a new error for the next box in the form. I'd like to see that all errors occur on the same button click. (the function trigger from a button).
The code below does not show the errors simultaneously. Is there any way to perform this without a loop? It feels like it should be, but I'm not sure how to move on.
function sum()
{
prem1 = document.formular.Uppgift1.value;
prem2 = document.formular.Uppgift2.value;
prem3 = document.formular.Uppgift3.value;
prem4 = document.formular.Uppgift4.value;
totpr = document.formular.priset.value;
varning1 = "name";
varning2 = "address";
varning3 = "phone";
varning4 = "phone number has to contain numbers";
varning5 = "e-mail";
varning6 = " - This one is not relevant to the input fields and should only show when thus are correct - ";
var re = /^[\w ]+$/;
if(!re.test(prem1)) {
document.getElementById('texterror1').innerHTML = (varning1);
form.inputfield.focus();
return false;
}
if(!re.test(prem2)) {
document.getElementById('texterror2').innerHTML = (varning2);
form.inputfield.focus();
return false;
}
if(!re.test(prem3)) {
document.getElementById('texterror3').innerHTML = (varning3);
form.inputfield.focus();
return false;
}
var re = /^(?=.*[0-9])\w{1,}$/;
if(!re.test(prem3)) {
document.getElementById('texterror4').innerHTML = (varning4);
form.inputfield.focus();
return false;
}
if(!re.test(totpr)) {
alert (varning6);
form.inputfield.focus();
return false;
}
var re = /^[\w ]+$/;
if(!re.test(prem4)) {
document.getElementById('texterror5').innerHTML = (varning5);
form.inputfield.focus();
return false;
}
else (alert ("Tack för din beställning " +prem1 + "! Här följer de uppgifter vi mottagit om dig. Adress: " +prem2 +" Tel.nr: " +prem3 +" E-post: " +prem4 +" Pris att betala: " +Discount +" kr" ));{
return true;
}
}
The code was translated on the relevant parts

Instead of returning false in each if statement, create a var to handle the error validation setting it to false in each failed if statement.
Only at the end of your function should you then return true or false by checking that var.

I would probably use a single variable failed setting it to false, only setting it to true in any one of the tests fail. But I would also use an array (an object) to store the error messages, using the ids as keys.
I would probably also store the regexes and original error messages in arrays. Using loops would be sensible though, to go through the elements and arrays.

Related

Do While Loop Mixed With Function Loop

I am writing a simple program for school and running into trouble with an issue I am hoping someone could help me with
These are the assignment parameters:
Create a small JavaScript program that:
Creates a variable 'total' with a value of 0.
Use a do-while loop & function to prompt the user to enter a series of numbers, or the word "quit" - the quit command should be case insensitive.
If the user enters a number, add the new number to a running total.
If the user enters the word "quit" the loop should stop execution.
If the user enters a word other than quit the prompt message should change to let the user know they entered an invalid data type
When the loop is exited, display a message giving the total of the numbers entered
My code achieves all assignment parameters except I can't figure out how to get the prompt to disappear after the quit command is entered. The result still displays on the screen but the prompt keeps looping.
Here is my code:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
You are calling the askForNum function from inside itself (recursion), in effect starting a new do-while loop inside the previous one every time you type anything other than "quit".

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

jquery hide/show or condiiton failing

Is there anything wrong with the jQuery/JS below? I have an input field aAmt which on change calls below. ${dAmt} = "10000" from DB. It basically converts the number to $ format(eg.. 23 to $23.00) and focuses the value to the input field. Issue is the if loop (if(aAmt >= a_amount)...) fails.
Even if the condition fails it goes to if loops and shows the div which should not happen. I don't see any error in developers console.
$('#aAmt').change(function() {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
curFormat(aAmt);
if(aAmt >= a_amount)
{
$("#dsDiv").show();
}else{
$("#dsDiv").hide();
}
});
function curFormat(aAmt)
{
var nAmt = Number(aAmt.replace(/[^0-9\.]+/g,""));
var fAmt = '$' + nAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
document.getElementById("aAmt").value = fAmt;
}
Have you tried to convert a_amount to an int, to be sure to compare two integers together:
var a_amount = parseInt("${dAmt}");

Need to get indexes from array and output them to user in JavaScript

We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;

javascript: counting digits in a text input

I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}

Categories