I might have it coded a bit wrong for the part I'm asking about but I'll give the solutions that work and the one that doesn't.
First example works:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value == document.UserSignUp.ConfirmEmail.value);
else {alert ("Your email does not match - Please re-enter"); return;}
if (document.UserSignUp.UserPassword.value == document.UserSignUp.ConfirmPassword.value);
else {alert ("Your password does not match - Please re-enter"); return;}}
This second example also works:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
else return true;}
But this last one doesn't work:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
else return true;
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{alert ("Your password does not match - Please re-enter"); return false;}
else return true;}
The interesting part about the last example is that the first confirm works but when I add and test out the second confirm, then it doesn't work and I'm not entirely sure why. As a side note, I tested out the second confirm on its own without the first and it worked fine. Has something to do with when a second one or more is added.
Any thoughts or suggestions of what I might be missing?
This is because you are returning in either of the if else case(1st) so the second if else wont be excuted.. :)
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
else return true;
//the execution doesnt reach this part of the code given below
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{alert ("Your password does not match - Please re-enter"); return false;}
else return true;}
In your last example, it will not reach the second if condition since you are returning true in the else condition of first if
function SignUpClick()
{
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value )
{
alert ("Your email does not match - Please re-enter"); return false;
}
else
return true; // this line will ensure that second if will not be reached
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{
alert ("Your password does not match - Please re-enter"); return false;
}
else
return true;
}
instead try this
function SignUpClick()
{
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value )
{
alert ("Your email does not match - Please re-enter");
return false;
}
else if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{
alert ("Your password does not match - Please re-enter");
return false;
}
return true;
}
That's because when you do a return, it ends the function right there, and does not continue to the final if/else statement
You use return in first if else which break the running code,
Try this -
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{
alert ("Your email does not match - Please re-enter");
return false;
}
else if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{
alert ("Your password does not match - Please re-enter"); return false;
}
else return true;
}
You just returned true or false on first if/else check. So when function runs it will return data anyway and never go to password check. Following will work:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value
!= document.UserSignUp.ConfirmEmail.value) {
alert ("Your email does not match - Please re-enter"); return false;
}
if (document.UserSignUp.UserPassword.value
!= document.UserSignUp.ConfirmPassword.value) {
alert ("Your password does not match - Please re-enter"); return false;
}
return true;
}
I went with AkshayJ answer because his made more sense. Essentially they said since I had a return in both the first If and first Else, that is why it didn't go to second If and Else. Basically you can have only one return per If & Else if you're gonna have multiple If & Else statements. I can confirm that because I had tried what others said such as taking out the False and True, I had also tried making it look like else {return true;} and else {return;}. So it had nothing to do with whether it had True or False and whether it had { }.
Though the ones saying that its just because of one return in any of the first If and Else or because any If and Else that has a return in the else statement... that's just wrong and a assumption. Its a assumption because of my first example proves that wrong by it showing a return in its Else and the 2nd If & Else worked.
Also when I tested out what AkshayJ said by changing the code to else {} or just simply taking out the Else statement, both ways let the second confirm work.
Plus to continue with two paragraphs/sentences above, a return can work in the If statement as well to let it go on to the second If, so it doesn't just work only in the Else:
function SignUpClick(){
if (document.UserSignUp.UserEmail.value != document.UserSignUp.ConfirmEmail.value)
{alert ("Your email does not match - Please re-enter"); return false;}
if (document.UserSignUp.UserPassword.value != document.UserSignUp.ConfirmPassword.value)
{alert ("Your password does not match - Please re-enter"); return false;}}
The above code works. Thanks for the info AkshayJ and thank you for everyone else that helped as well.
As side note for those that gave their example with a Else If, because of the context of what is in the If & Else, its bad practice to try to change the dynamic flow of how conditions are currently set up. Wasn't asking to combine them when they were already separate. For reference, go to here: w3schools.com/js/js_if_else.asp
So, yes the combine examples worked but its not what I asked about. Nor does it solve the fact that with those combine examples, it doesn't fix the problem if I were to add another If & Else statement. Since AkshayJ explained it, the answer goes to them, thanks again.
Related
Hi folks I was curious if someone could help me out. I don't usually post on here but I have exhausted all my efforts and can't figure this out. I have this code here
function insertVideo(link)
{
if (link)
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
var editpane = document.frmPost.addesc;
var linkcode = "[EMBED]" + link + "[/EMBED]";
editpane.focus();
/*if (document.selection)
{
document.selection.createRange().text = linkcode;
}
else*/
if (editpane.selectionStart || editpane.selectionStart == '0')
{
var selstart = editpane.selectionStart;
var selend = editpane.selectionEnd;
editpane.value = editpane.value.substring(0, selstart) + linkcode + editpane.value.substring(selend);
editpane.selectionStart = selstart + linkcode.length;
editpane.selectionEnd = editpane.selectionStart;
}
else
{
editpane.value = editpane.value + linkcode;
}
editpane.focus();
}
}
The problem I am having is when the user trys top post a youtube video with https in the address.
I understand that if I change
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
to
{
if(link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
It works. But then when the user enters the http address without the https it no longer works. I figured I could combine the statement with an OR, but this doesnt work either, I had
if(link.substring(0,29)!="http://www.youtube.com/watch?" || link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
So basically I need it to work in both situations (https and http) not just one or the other.
I am stumped, Im no pro with javascript so I sure its a minor error but I have spent far too much time trying to figure this out on my own. Please help if you can. Thanks!
It's as simple as changing the OR (||) to an boolean AND (&&).
if (link.substring(0,29) !== "http://www.youtube.com/watch?" && link.substring(0,30) !== "https://www.youtube.com/watch?") {
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
// the else is unnecessary
// else {
link = link.replace(/watch\?/,"").replace(/\=/,"/");
// }
This works as in your original code, if your URL is http://, it will fail the https:// check (or vice versa), making the conditional true, therefore running your failure code. Changing it to && fixes it as the URL is now required to fail both tests to be invalid.
Just a little note: unless you're doing it deliberately (or in other special circumstances), you should use the === and !== forms of equality testing (instead of == and !=), as these fail automatically if they are of different types instead of converting the types implicitly.
I'm using this code to validate a form:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
if (isEmpty(name)) {
alert("3");
return false;
}
if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
if (isEmpty(city)) {
alert("6");
return false;
}
if (isEmpty(comments)) {
alert("7");
return false;
}
When hitting the "Submit" button, if the first two conditions do work(The ones that check if the email var is empty or not in email address format) - meaning that if I leave the email input empty or not in an email address format I get the alert (1 or 2).
The problem is that the rest of the validations get skipped and it doesn't matter if I leave another input empty or not in format.
Also, if I take the first IF block:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
And move it to the end of the validation block, everything works just fine.
I'm guessing I have a wrong syntax somewhere but I spent 2 hours looking and just couldn't find it.
P.S.
here are the two validation functions I'm using:
function isEmpty(field) {
if ((field == null || field == "")) {
return true;
}
return false;
}
function isEmail(field) {
var atpos = field.indexOf("#");
var dotpos = field.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
return false;
}
}
You use x.length in the isEmail function, but x is not defined.
the return statement exits the function to get all the validations run
keep all the validations in if else if blocks and keep on using return false every time.
or
set a variable to false whenever condition fails and then return the value. as j00lz said.
The
return false;
ends the function and stops the rest of the code being executed.
Instead set a variable:
result="false";
and at the end of the function add
return result;
What happens if you change it to this:
if (isEmpty(email)) {
alert("1");
return false;
}
else if (!isEmail(email)) {
alert("2");
return false;
}
else if (isEmpty(name)) {
alert("3");
return false;
}
else if (isEmpty(age)) {
alert("4");
return false;
}
else if (!isAge(age)) {
alert("5");
return false;
}
else if (isEmpty(city)) {
alert("6");
return false;
}
else if (isEmpty(comments)) {
alert("7");
return false;
}
I'm just curious as to what happens if you make the whole thing one big if statement rather than breaking it up into parts, considering it's not going to change the validation process.
P.S.
I'm not sure if you realize or not, but with the way you have it set up, once one of the first if statements comes back false, returning false with in that if statement will end the whole method you're working in, meaning it won't run any other parts of it. So if you're shooting for displaying an alert for each and every empty input, etc, it won't happen this way.
I have a form to be filled in by the users, and empty fields would prompt JavaScript validation to return a message to fill in that specific field. I'm able to accomplish this all except that in spite of returning an "Alert" message, the form gets submitted. How do I avoid this? Here's my JavaScript:
function validateHandAppr(theForm) {
// Recom or Not Recom
if (document.project.rec.selectedIndex == 0) {
alert("Please Choose the Recommendation Priority .");
project.rec.focus();
return false;
}
// Recommended priorities
if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value == "") {
alert("Fill in the date when culture was received.");
project.recvd_dt.focus();
return false;
}
if (document.project.rec.selectedIndex == 2 && document.project.recvd_by.value == "") {
alert("Specify who received the culture.");
project.recvd_by.focus();
return false;
}
if (document.project.rec.selectedIndex == 2 && document.project.recvd_dt.value != "") {
var validformat = /^\d{4}\-\d{2}\-\d{2}$/; //.test(project.recvd_dt.value) //Basic check for format validity
if (!validformat.test(project.recvd_dt.value)) {
alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
return false;
} else { //Detailed check for valid date ranges
var yearfield = project.recvd_dt.value.split("-")[0]
var monthfield = project.recvd_dt.value.split("-")[1]
var dayfield = project.recvd_dt.value.split("-")[2]
var dayobj = new Date(yearfield, monthfield - 1, dayfield)
if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
return false;
} else {
return true;
}
}
}
}
Following is the form where JavaScript is being called:
<form accept-charset="UTF-8" id="project" name="project"
action="hand_submit_forms.php" method="post"
onSubmit="return validateHandAppr(this)"
class="user-info-from-cookie" enctype="multipart/form-data">
Following is the updated code,as per suggested by DaveRandom:
function validateHandAppr(theForm) {
// Recom or Not Recom
//var val=true;
if ( document.project.rec.selectedIndex == 0 )
{
alert ( "Please Choose the Recommendation Priority ." );
document.project.rec.focus();
return false;
}
// Recommended priorities
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value == "")
{
alert("Fill in the date when culture was received.");
document.project.recvd_dt.focus();
return false;
}
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_by.value == "")
{
alert("Specify who received the culture.");
document.project.recvd_by.focus();
return false;
}
if ( document.project.rec.selectedIndex ==2 && document.project.recvd_dt.value != ""){
var validformat=/^\d{4}\-\d{2}\-\d{2}$/ ; //.test(project.recvd_dt.value) //Basic check for format validity
if (!validformat.test(project.recvd_dt.value))
{
alert("Invalid Date Format. Please enter in the following format: yyyy-mm-dd.")
return false;
}
else{ //Detailed check for valid date ranges
var yearfield=project.recvd_dt.value.split("-")[0]
var monthfield=project.recvd_dt.value.split("-")[1]
var dayfield=project.recvd_dt.value.split("-")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
{
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
return false;}
else
{
return true; }
}
}
// return val;
}
The problem is these lines:
project.rec.focus();
// ...
project.recvd_dt.focus();
// ...
project.recvd_by.focus();
Your validation conditions reference document.project but the above lines represent simply project - which does not exist globally because it is a child of document, not window and you did not declare it locally.
Because these lines are between the alert() lines and the return false; lines, you will see the alert but the return statement will never be reached - so the function will not return false and the form will be submitted.
If you change the lines to:
document.project.rec.focus();
// ...
document.project.recvd_dt.focus();
// ...
document.project.recvd_by.focus();
...it should work.
However
You should assign the functions to the <form>s DOM object's submit event instead of using inline event handlers.
If you do this, you will be passed an event object to the first argument of the function, and you can use event.preventDefault() instead of returning false. This would avoid the problem (if the line was placed before the error occurred), and is generally a better way to handle this, because returning false also stops propagation of the event, which may not be desired - actually this makes little difference in this specific case but as a general rule it is true.
If you do this, the handler will be executed in the context of the DOM object - so the this variable will be a reference to it, and you won't need to pass it in as an argument.
I'm teaching myself JavaScript using Code Academy and I'm trying to make some simple code so that when prompt asks a question, the user reply gives a response.
example.
prompt says "what's your favourite colour?"
user says "blue"
response "that's the same colour as the sky!"
But when I try to add different options, I get Syntax error: unexpected token else.
I tried making it so that if I asked a question, the reply gets a response but anything else gets a response.
Here's the code.
prompt("what do you want?");
if ("coke");
{console.log ("no coke, pepsi.")};
else
console.log ("pepsi only.")};
If anyone has any ideas, I'd be very grateful!
Disclaimer: I don't work for Coca Cola.
You need to save the return value of prompt if you want to use it later. Also, you have some syntax errors that should be corrected:
var answer = prompt('what do you want?');
if (answer === 'coke') {
console.log('you said coke!');
} else {
console.log('why didn\'t you say coke!?');
}
You could also use a switch as you get more cases:
var answer = prompt('what do you want?');
switch (answer) {
case 'coke':
console.log('you said coke!');
break;
default:
console.log('why didn\'t you say coke!?');
break;
}
Or an object, as most people prefer this to switch:
var answer = prompt('what do you want?');
var responses = {
coke: 'you said coke!',
defaultResponse: 'why didn\'t you say coke!?'
};
console.log(responses[answer] || responses.defaultResponse);
The if does not need a semicolon at the end. Instead do:
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
Remove the trailing semicolons:
prompt("what do you want?");
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
You have a semi-colon after the close brace. Try:
var ans = prompt("what do you want?");
if (ans == "coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
var name = prompt("what do you want?");
if (name == "coke")
{
console.log ("no coke, pepsi.")
}
else
{
console.log ("pepsi only.")
}
Like above
Actually DO NOT do
if (ans == "whatever") {
console.log ("whatever");
} else {
console.log ("whatever.");
}
DO
if (ans == "whatever") {
confirm ("whatever");
} else {
confirm ("whatever.");
}
A variable needs to be identified. Also the bracketing and the semi colons between the "if" "else" statements are problematic. I am not sure about the console log, but if you want a popup alert try this:
var brand = prompt ('what do you want?');
if (brand="coke") {
alert ("no coke, pepsi.")
}else {
alert ("pepsi only.")
};
DICLAIMER: I am novice at best, jut happened to debug a similar issue.
Hope it helps.
I have variable deleteboxvalue
var deleteboxvalue = "111111111111111";
if(deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected."); return true;
}
I want to check if 0 is not exist in this I want to return false and alert as "You can't delete all Contact Number." but in both cases if 0 exist in variable in that case also its returning false and giving me alert as "You can't delete all Contact Number."
I want to check if 0 is not exist in this I want to return false
If that's the case then you've got your logic reversed. You are currently returning false if 0 is in the string (i.e. it is found at an index greater than or equal to 0). If you want to return false when 0 is not found in the string, you can do this:
if(deleteboxvalue.indexOf('0') == -1) {
alert("You can't delete all Contact Number.");
return false;
}
else {
alert("All Zeros are not selected.");
return true;
}
However, I may have completely misunderstood what you're trying to do...
Create a function in JavaScript such as:
function CheckContacts() {
var deleteboxvalue = "111111111111111";
if (deleteboxvalue.indexOf('0') >= 0) {
alert("You can't delete all Contact Number.");
return false;
} else {
alert("All Zeros are not selected."); return true;
}
}
and
On body onload call that JavaScript method:
<body onload="CheckContacts()">