If statements not initialising JavaScript - javascript

Here is my code for a simple HTML form with JavaScript Validation. I simply want to return an error message if the fields are blank.
At the moment the page just goes straight to the success.html page without initialising the javascript. Any help would be greatly appreciated!
Ok so I've made some changes and its still not working. Here is the edited code:
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value==="") {
msg+="You must enter your name \n";
document.ExamEntry.Name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value==="") {
msg+="You must enter the subject \n";
document.ExamEntry.Subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(msg===""){
return result;
}else{
alert(msg)
return result;
Thanks for all the contributions

The curly parentheses surrounding the logic following the below if statement are invalid
if (msg !== "") {
return result;
} {
alert(msg)
return result;
}
Simply, you should write:
if (msg !== "") {
return result;
}
alert(msg);
return result;

Am I reading this wrong or are your if statement logic backwards?
if (document.ExamEntry.name.value !== "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value !== "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
result by default is true. If you fail to enter a value for either fields, then !== "" will be false (because it does equal the empty string) and therefore result will be left true, which enables form submission.
Try:
if (document.ExamEntry.name.value === "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value === "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
Also, as others pointed out, you are missing an else statement:
if (msg !== "") {
return result;
} else {
alert(msg)
return result;
}
And finally, you mentioned this is Java. This is JavaScript. And no, JavaScript is not just a smaller version of Java. It is a very different language.

It looks like you are comparing with non-empty string while the comparision should have been for an empty string i.e.,if (document.ExamEntry.name.value !== "") { should be changed to if (document.ExamEntry.name.value == "") {
This implies to check for a a non empty string in the text box and redirect to the appropriate page (success page).
Also move the alert(msg) to the if (msg !== "") block. I think you would want to alert the user in case of empty text box.

Related

prompt function does not accept input which only contains numbers

I have added confirmation dialog to input again the status I get before submitting.
That park works.
Problem is that prompt() function does not except inputing just numbers?
Is there anyway I can added that part to so it can pass?
$(".delete-status").click(function (ev, el) {
var status = $(this).data("status");
var statusInput = prompt("Confirm deletion by entering the status:");
if (statusInput === status) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
});
Any idea how to fix the code? I am pretty new at jQuery and JS. Thanks
I want to cover both cases. With string and with number.
jQuery's .data() method automatically parses the data as JSON if it can, so if it looks numeric it will return a number, not a string.
prompt() always returns a string (or null if you cancel).
So you need to convert status and statusInput to the same type if you want to compare them with ===. You can use parseInt() to convert the user input to an integer.
$(".delete-status").click(function(ev, el) {
var status = $(this).data("status");
var statusInput = parseInt(prompt("Confirm deletion by entering the status:"));
if (statusInput === status) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
});
You could convert statusInput string to a number.
This could be better but something along the lines of:
$(".delete-status").click(function (ev, el) {
var status = $(this).data("status");
var statusInput = prompt("Confirm deletion by entering the status:");
if (Number(statusInput) === Number(status)) {
statusDelete(status);
} else if (statusInput === null || statusInput === "") {
alert("Field should not be empty!");
} else {
alert("Entered status and status don't match!");
}
})

if and else statements inside a while loop won't work

I'm trying to create an alert asking about the user email and if it's compatible to the stored variable, Then an alert will appear with Logged! message but the loop doesn't work with my code only if and else does but only for one time.
//working code
function validation(str) {
var str = prompt("Please Enter your email");
var email = "plapla#gmail.com";
if (str === email) {
return alert("Welcome back, Logged Successfully!" + " your email is " + str);
} else {
return alert("Your Email is incorrect, Please Try again");
}
}
validation();
//Loop Code
function validation(str) {
var str = prompt("Please Enter your email");
var email = "plapla#gmail.com";
while (str !== email) {
if (str === email) {
return alert("Welcome back, Logged Successfully!" + " your email is " + str);
} else {
return alert("Your Email is incorrect, Please Try again");
}
str++;
}
}
validation();
The variable str is not being updated in your loop. Your also using a return statement that will stop the loop after its first iteration.
You need to use prompt("") inside your loop and the condition to continue this loop is str !== email
If the message from the prompt is the same as the email, the loop will stop and code after the while will execute
var str = prompt("Please enter your email");
var email = "test";
while (str !== email) {
str = prompt("Please enter a valid email");
}
alert("Yeah ! Hello !");
I believe this is what you intended to achieve
function validation() {
var str = prompt("Please Enter your email");
var email = "plapla#gmail.com";
do {
if (str === email) {
alert("Welcome back, Logged Successfully!" + " your email is " + str);
} else {
str = prompt("Your Email is incorrect, Please Try again");
}
} while (str !== email)
}
validation();
You have to get the value each time you iterate, otherwise str isn't updated. To do so I used a do...while loop to execute it at least once, and loop while the user hasn't entered a correct value.
I removed str++ from your code since it doesn't mean anything to increment (++) a string value.
I changed a bit your concatenation inside the alert to something more concise.
I also removed the return statements because they would stop the execution of the function and it's not what you want.
function validation() {
do {
var str = prompt("Please enter your email");
var email = "plapla#gmail.com";
if (str === email) {
alert("Welcome back, Logged Successfully ! Your email is " + str);
} else {
alert("Your email is incorrect, please try again");
}
} while (str !== email)
}
validation();

Create multiple JavaScript variables?

I am new to JavaScript. Can someone please tell me what I am doing wrong? I have created an error message for an HTML form. The name field works, but I want to create an individual message if other fields are left blank.
Below is my JavaScript code:
function validateForm() {
var name = document.forms["contactform"]["name"].value;
if (name == "")
var email = document.forms["contactform"]["email"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
return false;
document.getElementById('erroremail').innerHTML = "Please enter your email";
return false;
}
}
Syntactically:
This code is not reached: document.getElementById('erroremail').innerHTML = "Please enter your email";
Put it before the first return and remove the second return.
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
document.getElementById('erroremail').innerHTML = "Please enter your email";
return false;
}
Logically:
Why would you test twice the same exact thing?
Solution:
Test for empty email => do something
Test for empty name => do something
The problem in your code is that you return something before checking another validation. When you return something, the function stops and nothing after return gets validated.
In your situation,you can declare a variable which is true by default var ret=true; and if a condition doesn't meet your requirements it becomes false.
For example:
function test() {
var ret = true;
if( 1 !== 1 ) {
ret = false; //you will return false in the end
}
return ret; //return the result. from this point on, the function exits and doesn't do anything after
alert("This will not be executed because there is a 'return' before");
}
The above function will return false and it will not execute the alert because you already return a result from that function
What you need is:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
ret = false;
}
var email = document.forms["contactform"]["email"].value;
if (email== "") {
document.getElementById('erroremail').innerHTML = "Please enter your email";
ret = false;
}
return ret;
}

Javascript convert alert to string

I have this small javascript to validate form input.
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
I'm tryin to figure out how to get the "alert" message as a string to show it later on the page instead of popping this ridiculous box. Looks simple to me but i'm a big zero in js. Any help appreciated, Thanks !
The alert() method is what makes the big pop up box. If you want to save the value for later use save it to a variable. Something like:
var message = "";
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
message = "Some fields need correction:\n" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
var alerter;
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmail(theForm.courriel);
if (reason != "") {
alerter = "Some fields need correction:<br/>" + reason;
return false;
}
return true;
}
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
document.body.innerHTML = alerter;
How about assigning the string to a property of "window" :
window.myAlert ="Some fields need correction:\n" + reason);
Then you can get it from anywhere:
document.body.innerHTML = window.myAlert;

JS email validation still submits invalid emails

I have a field where a user can submit multiple emails delimited by a comma character. I want JS validation to achieve two things:
If user tries to submit nothing, they get an alert that they have to enter an email, this WORKS
If user tries to submit any number of emails where one email is incorrectly formatted, they get an alert that one email has been improperly formatted, and they have to resubmit, this DOES NOT WORK
What happens with #2 is that if I submit something bogus like asddf as an email, I:
DO get the alert yay!
However, the form still gets submitted, BOO
Code:
$("#refer").click(function() {
var input_emails = $('#friend_emails').val();
if (input_emails === "") {
alert("Please enter at least one friend's email to send invites")
return false;
} else {
var parsed_emails = input_emails.split(',');
$.each(parsed_emails, function( index, email_value ) {
var trimmed_email = $.trim(email_value)
var atpos = trimmed_email.indexOf("#");
var dotpos = trimmed_email.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=trimmed_email.length) {
alert(trimmed_email + " " + "is not a valid email format, please correct and resubmit");
return false;
}
});
}
});
the return in your $.each(... is returning from the internal function. you need a way to return false from your outer function. something like this
$("#refer").click(function() {
var input_emails = $('#friend_emails').val();
if (input_emails === "") {
alert("Please enter at least one friend's email to send invites")
return false;
} else {
var success = true;
var parsed_emails = input_emails.split(',');
$.each(parsed_emails, function( index, email_value ) {
var trimmed_email = $.trim(email_value)
var atpos = trimmed_email.indexOf("#");
var dotpos = trimmed_email.lastIndexOf(".");
if (atpos< 1 || dotpos=trimmed_email.length) {
alert(trimmed_email + " " + "is not a valid email format, please correct and resubmit");
success = false;
}
});
return success;
}
});

Categories