JavaScript redirect in modal - javascript

I've been struggling with this for a while but I can't seem to figure this out.
I've got a modal that displays and asks for user login and password. Right now if user ==admin it should redirect to Google but for some reason it doesn't work.
Any indications on why is this happening?
<form id="loginform" name="loginform" method="post" action="index.html">
<label for="username">Username:</label>
<input type="text" name="username" id="username" class="txtfield" tabindex="1">
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="txtfield" tabindex="2">
<div class="center">
<input type="submit" name="loginbtn" id="loginbtn" class="flatbtn-blu hidemodal" value="Log In" tabindex="3">
</div>
</form>
</div>
<script type="text/javascript">
$(function() {
$('#loginform').submit(function(e) {
});
$('#modaltrigger').leanModal({
top: 110,
overlay: 0.45,
closeButton: ".hidemodal"
});
});
$('#loginbtn').click(function() {
var username = $("#username").val();
var password = $("#password").val();
if (username == "admin") {
window.location.href = "http://kegan.ing.puc.cl/~grupo6/faseiv/index.php";
} else {
alert("Usuario o contraseña invalido");
}
});

OK, looking at it first, your $('#loginbtn') code is outside your DOM ready scope. Secondly, I'd remove that selector completely and bind your code to the form's submit event - it's much more accurate than the submit buttons click.
$(function() {
$('#loginform').submit(function(e) {
e.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
if (username == "admin") {
window.location.href = "http://kegan.ing.puc.cl/~grupo6/faseiv/index.php";
} else {
alert("Usuario o contraseña invalido");
}
});
});
...if you were to continue to use the click handler on your submit button, you need to stop #loginform from submitting normally.

Related

function not working on "submit" event, but works when ran in dev console

I am rendering the form below, and below that I have a script. When I load the page, type in the email and password, then submit, it appears to just reload the page (regardless of credentials).
When I type in the email and password, and then execute the function in the dev console by typing loginUser() it executes as expected and if creds are correct it redirects me as it should. If credentials are wrong the alert events fire.
I have put in breakpoints, and on "submit" it gets the email and password that are in the form, but then seems to jump back up to the start of the function (regardless of credentials).
let form = document.getElementById('loginform');
form.addEventListener('submit', loginUser);
function loginUser() {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).then(() => {
window.location.href = "/";
}).catch(error => {
console.log(error)
let errorCode = error.code;
let errorMessage = error.message;
if (errorCode == 'auth/wrong-password') {
window.alert('Entered password was incorrect.');
} else if (errorCode == 'auth/user-not-found') {
window.alert('Entered email is invalid.');
} else {
window.alert('Please check your login credentials.');
}
});
};
firebase.auth().onAuthStateChanged(user => {
if (user) {
console.log(user)
user.getIdToken().then(function(token) {
//save the token in a cookie
document.cookie = "token=" + token;
});
} else {
console.log("What up dude?");
}
});
<form id="loginform" action="" method="post">
<div class="form-group">
<label for="email">Email</label> <input class="form-control" id="email" name="email" required="required" type="text" value="">
</div>
<div class="form-group">
<label for="password">Password</label> <input class="form-control" id="password" name="password" required="required" type="password" value="">
</div>
<div class="form-group">
<input class="btn btn-primary" id="submit" name="submit" type="submit" value="Login">
</div>
</form>
It is imperative to REMOVE or RENAME id="submit" name="submit"
Calling anything submit in a form hides the submit method
Then add preventDefault() to stop submission:
function loginUser(e) {
e.preventDefault()

Open target.html page within SAME window following successful login [duplicate]

This question already has answers here:
How do I redirect to another webpage?
(58 answers)
Closed 3 years ago.
After inputting login details i would like the target.html page to load in the same window. Currently it loads in a new tab.
<body>
<div class="loginbox">
<img src="images/avatar.png" class="avatar">
<h1>Login</h1>
<form>
<p>Username</p>
<input type="text" name="userid" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="pswrd" placeholder="Enter Password">
<input type="submit" onclick="check(this.form)" value="Login">
</form>
<script language="javascript">
function check(form) {
if (form.userid.value == "username" && form.pswrd.value == "password") {
window.open('target.html')
} else {
alert("Error Password or Username")
}
}
</script>
</div>
</body>
Use window.location:
window.location.href = 'target.html';
Because the button is in a form, you must also cancel the default behavior of the event with e.preventDefault(). Here's a full example:
function check(e) {
e.preventDefault();
if (e.target.form.userid.value == "username" && e.target.form.pswrd.value == "password") {
window.location.href = 'target.html';
} else {
alert("Error Password or Username")
}
}
<div class="loginbox">
<img src="images/avatar.png" class="avatar">
<h1>Login</h1>
<form>
<p>Username</p>
<input type="text" name="userid" placeholder="Enter Username">
<p>Password</p>
<input type="password" name="pswrd" placeholder="Enter Password">
<input type="submit" onclick="check(event)" value="Login">
</form>
</div>
You can keep the type="submit" and use:
form.addEventListener('submit', function(event) {
event.preventDefault();
if (form.userid.value == "username" && form.pswrd.value == "password") {
window.open('target.html', '_self');
} else {
alert("Error Password or Username");
}
}, false);

jQuery to Send Email from Form?

I'm trying to have my form send me an email every time the "Submit Query" button is clicked. The form is validated and brings the user to a confirmation page after the button is clicked, but I get no email.
Form code:
$(document).ready(function() {
$('#sumbit').click(function() {
$('#contactform').attr('action',
'mailto:chinochinako#gmail.com?subject=Jeannette Chambliss Digital Portfolio' +
$('#name').val() + '&body=' + $('#email').val() + '&body=' + $('#comments').val() + '&body=');
$('#contactform').submit();
});
});
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://malsup.github.io/min/jquery.cycle2.min.js"></script>
</head>
<body>
<form onSubmit="MM_validateForm('name','','R','comments','','R');return document.MM_returnValue" id="contactform">
<label for="name">Full Name:
<input name="name" type="text" id="name" required="required"></label><br /><br />
<label for="email">Email:
<input name="email" type="email" id="email" required="required"></label><br /><br />
<label for="comments">Comments:
<textarea name="comments" id="comments" required></textarea></label><br /><br />
<input name="submit" type="submit" id="submit" formaction="confirmation.html" formmethod="POST" formtarget="_self" action="mailto:chinochinako#gmail.com">
</form>
<script src="js/form.js"></script>
</body>
</html>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var contact = $("#contact").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || contact == '') {
alert("Please Fill Required Fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contact_form.php", {
name1: name,
email1: email,
message1: message,
contact1: contact
}, function(data) {
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Your Query has been received, We will contact you soon.") {
$("#form")[0].reset(); // To reset form fields on success.
}
});
}
});
});
</script>
$(function() {
$('#contactform').submit(function(e) {
e.preventDefault();
$(this).attr(
'action',
'mailto:rafaeljunqueira.rs#gmail.com?subject=Jeannette Chambliss Digital Portfolio');
console.log($(this)[0].action);
return true;
});
});
form ul {
padding: 0;
margin: 0;
}
form ul li {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="text/plain" id="contactform">
<ul>
<li>
<input type="text" placeholder="Name" id="name" />
</li>
<li>
<input type="text" placeholder="Email" id="email" />
</li>
<li>
<input type="text" placeholder="Comments" id="comments" />
</li>
</ul>
<button type="submit" id="submit">Send</button>
</form>
Welcome to Stack Overlfow.
I suspect you are missing the .preventDefault() to prevent the click event from proceeding.
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$('#contactform').attr(
'action',
'mailto:chinochinako#gmail.com?subject=Jeannette Chambliss Digital Portfolio');
$('#contactform').submit();
});
});
Mind you, if the user bypasses clicking the button, and hits Enter, this code will not execute. You may want to consider moving your verification code into the submit event in jQuery, and move this code in there too.
I noticed a potential typo: $('#sumbit').click(function() {
Did you mean: $('#submit').click(function() {
Update
According to the HTML specifications, the action field of the form should be a correctly formed HTTP URL. So ‘mailto:’ is not valid for the action field.
Also, this will not "send" the email. It will only ask the default email program to compose a message that the user can send. If you want the data submitted to be sent via SMTP, this must be done by a server-side script (ASP/ASP.NET, PHP, ColdFusion, Perl, Python...) via a form handler.
$(function() {
$('#contactform').submit(function(e) {
e.preventDefault();
$(this).attr(
'action',
'mailto:chinochinako#gmail.com?subject=Jeannette Chambliss Digital Portfolio');
console.log($(this)[0].action);
return true;
});
});
form ul {
padding: 0;
margin: 0;
}
form ul li {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="text/plain" id="contactform">
<ul>
<li>
<input type="text" placeholder="Name" id="name" />
</li>
<li>
<input type="text" placeholder="Email" id="email" />
</li>
<li>
<input type="text" placeholder="Comments" id="comments" />
</li>
</ul>
<button type="submit" id="submit">Send</button>
</form>

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

Check if form is completed before activating submit button

I am creating a form where a user has to fill out several fields and then click sign up. However, I want JavaScript to check if the passwords match, and if they don't or a field is left empty to put the signup button into a disabled state with Bootstrap. However, nothing is working. Here is my code:
JSFIDDLE: http://jsfiddle.net/jbe65/
echo '
<h3>Don\'t have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<br><br>
<p id="submit">button class="btn btn-primary btn-block" type="submit">Sign Up/button></p>
</form>
<script>
var empty = "";
var email = $(\'#email\').val()\;
var pass = $(\'#pass\').val()\;
var passver = $(\'#passver\').val()\;
if (empty == email)
{
if (pass != passver)
{
document.getElementById("submit").innerHTML=\'<button class="btn btn-primary btn-block" type="submit" disabled="disabled">Sign Up</button>\';
}
}
</script>
';
I will suggest make the button lookalike disable (by css) and once all the cond pass can make it enable (by css)..
$(document).ready(function () {
$("#formid").on("submit", function (e) {
var empty = "";
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if (empty == email || pass !== passver)
{
alert("please enter valid email and password.");
e.preventDefault();
}
else
{
//u can call this in textbox blur also...
$("#sub").removeClass("disable");
}
});
});
Fiddle Demo
I'm assuming you are using PHP. If so, you can replace the echo statement with a closing PHP bracket ?> to escape the parser. It's generally easier to deal with.
To answer the question at hand, since you are using jQuery, there is no need to change the innerHTML of the p tag, just use the .prop() function, like so:
?>
<h3>Don't have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<p id="submit"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></p>
</form>
<script>
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if ("" == email)
{
if (pass != passver)
{
$('#submit button').prop('disabled', true);
}
}
</script>
<?php
If you're using HTML5 , Put "Required" and then the submit button will not be loaded if there is an empty field Ex :

Categories

Resources