How do you load a separate .html page with Javascript [duplicate] - javascript

This question already has answers here:
How do I redirect to another webpage?
(58 answers)
Closed 3 years ago.
I am trying to figure out how to send a user to another page I design after they have input the correct password. I don't know how to load the page with a JavaScript Command. How could i use the code below to open a new page titled insideVault.html?
I have tried many google searches, but cant find any resources to help me out with this.
// login code //
<div class = "container">
<div class = "passwordEnter">
<div class = "text-center">
<form id="login" onsubmit="return passCheck()" method="get">
<p> Enter Password </p>
<input type="password" name="password" id = "password">
<input type="submit">
</form>
</div>
</div>
</div>
<script src="script.js"></script>
</div>
<script>
function passCheck(){
var input = document.getElementById("password").value == 'test';
console.log(input);
if(!input){
alert('Password incorrect, please try again.');
return false;
}
return true;
}
I want the code to load a new page, but so far I have not been able to find any code that would allow me to do this.

Try location.href:
function passCheck(){
var input = document.getElementById("password").value == 'test';
console.log(input);
if(!input){
alert('Password incorrect, please try again.');
return false;
}
location.href = 'insideVault.html';
}

Related

JavaScript Login Form Not Validating

Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation

Validate form's textarea - jQuery

I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.
I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.
This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:
<form id="colleagues" action="email-sent.php" method="POST">
<input type="hidden" name="user" value="user" />
<textarea id="emails" name="emails" value="emails" placeholder="Example: john#mail.com, thiffany#mail.com, scott#mail.com..."></textarea>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
Here is what I tried in Jquery with no success:
//handle error
$(function() {
$("#error_message").hide();
var error_emails = false;
$("#emails").focusout(function() {
check_email();
});
function check_email() {
if(your_string.indexOf('#') != -1) {
$("#error_message").hide();
} else {
$("#error_message").html("Invalid email form.Example:john#mail.com, thiffany#mail.com, scott#mail.com...");
$("#error_message").show();
error_emails = true;
}
}
$("#colleagues").submit(function() {
error_message = false;
check_email();
if(error_message == false) {
return true;
} else {
return false;
}
});
I hope the question was clear enough, if you need more info please let me know.
Many thanks in advance for all your help and advises.
var array = str.split(/,\s*/);
array.every(function(){
if(!validateEmail(curr)){
// email is not valid!
return false;
}
})
// Code from the famous Email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Few errors as I noted down:
The code snippet posted here has missing braces }); at the end.
Also, what is your_string variable in the function check_email.
Also, error_message is assigned false always so the submit method will return true always.
Fixing this issues should help you.
I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():
<form id="colleagues" action="" method="POST">
<input type="hidden" name="user" value="user" />
<input name="emails[]" id="starter" placeholder="Email address" />
<div id="addEmail">+</div>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function() {
$("#addEmail").click(function() {
$("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
});
});
</script>
Hi please use below js code,
$('#emails').focusout(function(e) {
var email_list = $('#emails').val();
var email_list_array = new Array();
email_list_array = email_list.split(",");
var invalid_email_list=' ';
$.each(email_list_array, function( index, value ) {
if(!validEmail(value))
{
invalid_email_list=invalid_email_list+' '+value+',';
}
});
console.log(invalid_email_list+' is not correct format.');
alert(invalid_email_list+' is not correct format.');
})
function validEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.
thank you
Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...

HTML text input conditional submit

I have a page that loads a random MP3 file on each refresh. The user has to guess a name based on the sound via text form input. I want to check their input against the stored string and refresh the page if it's correct. Otherwise, I wan't to give them an incorrect alert and stay on the same page so they can guess again:
<div class="ui-widget" align="center">
<form method="post" action="" class="answer_box" onsubmit="return submit();">
<p>Which hero is it? <input id="tags" name="guess" /></p>
<script>
var key = <?php echo json_encode($rand_key) ?>;
var info = document.getElementById("guess").value;
function submit() {
if (key==info){
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
</form>
</div>
Right now, it submits the information to a new page regardless of the input. The javascript alerts are also not showing (I suspect they do show, but the page then refreshes and they disappear). The key variable is the key from the randomly taken value of a PHP array, and info should be the text the user inputs.
Problems found:
you cant use submit as a function name a this is an HtmlForm object
document.getElementById("guess").value; is looking for an element with ID of "guess" and that does not exist.
I would rewrite your script like this:
<script>
var key = <?php echo json_encode($rand_key) ?>;
function my_submit(curr) {
var info = curr.guess.value;
if (key == info) {
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
<form onsubmit="return my_submit(this);">
<p>Which hero is it? <input id="tags" name="guess"/></p>
</form>
You have a problem here:
<input id="tags" name="guess" />
Your id is tags, not guess.
You should use document.getElementById("tags").value.
You are trying to retrieve the value of an element with id of "guess." Change this to "tags."
var info = document.getElementById("tags").value;
Also, as #CodeGodie mentioned, you need to change your function name to something other than submit.

Javascript code not working unless there are no spaces. Why?

Ok so I am running into a really weird bug on my Wordpress site that hope is just my ignorance because this just seems too weird.
So I am working with styling a couple of input tags as well as a ReCaptcha form. I found some documentation at https://developers.google.com/recaptcha/old/docs/customization that I have been following. Basically what I want is the clean theme listed at that link and to do some showing/hiding of the captcha based on certain events.
I do realize that the top of the article mentions this version of the api is old, but the plugin I am using has some recaptcha code entangled in their code, so I figured I would try this first instead of making major modifications to the plugin.
So here is the code I am using
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
<!-- End code added by me -->
<script>
function validateGoodNewsUser(frm, requireName) {
requireName = requireName || false;
if(requireName && frm.goodnews_name.value=="") {
alert("Please provide name");
frm.goodnews_name.focus();
return false;
}
if(frm.email.value=="" || frm.email.value.indexOf("#")<1 || frm.email.value.indexOf(".")<1) {
alert("Please provide a valid email address");
frm.email.focus();
return false;
}
// check custom fields
var req_cnt = frm.elements["required_fields[]"].length; // there's always at least 1
if(req_cnt > 1) {
for(i = 0; i<req_cnt; i++) {
var fieldName = frm.elements["required_fields[]"][i].value;
if(fieldName !='') {
var isFilled = false;
// ignore radios
if(frm.elements[fieldName].type == 'radio') continue;
// checkbox
if(frm.elements[fieldName].type == 'checkbox' && !frm.elements[fieldName].checked) {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
// all other fields
if(frm.elements[fieldName].value=="") {
alert("This field is required");
frm.elements[fieldName].focus();
return false;
}
}
}
}
return true;
}
</script>
<form method="post" class="goodnews-front-form" onsubmit="return validateGoodNewsUser(this,false);">
<div><label>Your Name:</label> <input type="text" name="goodnews_name"></div>
<div><label>*Your Email:</label> <input type="text" name="email" onfocus="toggleCaptcha(this)"></div>
<p><script type="text/javascript" src="<!--Captcha api url here-->"></script>
<noscript>
<iframe src="<!--Captcha api url here-->" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript></p>
<div><br>
<input type="submit" value="Subscribe">
</div>
<input type="hidden" name="goodnews_subscribe" value="1">
<input type="hidden" name="list_id" value="1">
<input type="hidden" name="required_fields[]" value="">
</form>
So the problem I am running into is when I load the page, I see the clean theme for ReCaptcha and the alert shows up when I click inside the input box for the email. But if I change my added code by adding a single space like this
<!-- Code added by me-->
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
<<<<<<<< Single new line space added.
function toggleCaptcha(inputField)
{
alert('working');
}
</script>
The whole thing breaks and the page loads with the standard red ReCaptcha and my functions don't get called.
I don't mind not using spaces, but that seems very odd that a space would make the difference. Am I missing something here? Is this caused by the outdated api?
Edit:
I was asked to try to get a jsfiddle working (or not working???). I stripped out everything except the form and the function call. Even the ReCaptcha was taken out and I still can not get it to call the function. This may be my lack of knowledge on jsfiddle or it may get closer to the real problem. https://jsfiddle.net/b257779t/

onSubmit button won't load location

I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.

Categories

Resources