I have been practicing basic programming with Bootstrap, HTML, CSS, and JavaScript and for the moment I'm doing a website that starts with a landing page that asks for a password and then sends you to another page.
The thing is that the form and the JavaScript validation aren't working together and I don't know why and what I'm doing wrong, so If someone could help me it would be awesome! Thanks!
<div class="jumbotron">
<form name="PasswordField" action="">
<div class="form-group">
<label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="isValid()" class="btn btn-default">Submit</button>
</form>
</div>
<script type="text/javascript">
function isValid(password)
{
var pass ="seahorse";
var password = document.getElementById("password");
if (password.value.toUpperCAse().match(pass))
{
window.location.href = "HappyChristmas.html";
return true;
}
else
{
alert('Nope, try again');
return false;
}
}
</script>
You're not calling isValid() when submitting the form.
You're transforming your input value toUpperCase() and checking if it matches a lowercase password "seahorse".
Check the snippet I made according to your code and it's running fine and dandy.
I added onclick call on your submit button so that it calls your isValid() function.
Also it's worth mentioning that you're passing a parameter to your isValid() function, but you don't need to because you're retrieving the password element and its value directly inside the function.
Another thing worth mentioning is that you're returning a boolean for the function but you don't really need to because you're not doing conditions in your script and when changing location on window.location or alert() the code will be stopped.
function isValid()
{
var pass = "seahorse";
var password = document.getElementById("password");
if (password.value.match(pass))
{
window.location.href = "HappyChristmas.html";
}
else
{
alert('Nope, try again');
}
}
<div class="jumbotron">
<form name="PasswordField" action="">
<div class="form-group">
<label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="isValid()" class="btn btn-default">Submit</button>
</form>
</div>
First Add the event to the form to call your javascript function
<form name="PasswordField" action="/where/to/go" onsubmit="return isValid()">
Second remove the argument from the function definition function isValid(password){ ... } because you are overwriting it with the dom node (var password = document.getElementById("password");)
Third this can be changed
if (password.value.toUpperCAse().match(pass)){
to this
if (password.value.toUpperCase() == pass.toUpperCase()){
Two reasons:
1. You're not calling the isValid function from anywhere and 2. You don't have a argument password to add into the function. Give this a try:
<div class="jumbotron">
<form name="PasswordField" action="">
<div class="form-group">
<label for="exampleInputPassword1"><h4>If you're an octopus I am...</h4></label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<-- Add an ID to the button -->
<button type="submit" id="submitBtn" class="btn btn-default">Submit</button>
</form>
<script type="text/javascript"
const pass ="seahorse"
const password = document.getElementById("password");
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", e=>{
e.preventDefault();
isValid();
})
function isValid() {
if (password.value.toLowercase().match(pass)){
window.location.href = "HappyChristmas.html";
return true;
}
else{
alert('Nope, try again')
return false;
}
}
</script>
Related
I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!
This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is
<button type="submit" id="btn" onclick="validate()">login</button>
However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
HTML
<div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
JS
//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not
function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem
Firstly its not
document.getElementById('password');
value;
its
document.getElementById('password').value;
Secondly, there is no action property present I'll suggest removing the entire form tags
<div class="wrapper">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type=" submit" id="btn" onclick="validate()">login</button>
</div>
<script>
function validate() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
if (username == 'please' && password == 'work') {
alert('finally');
} else {
alert("NOOOO")
}
}
</script>
on your for, you are using attibute method="post" which has alternative of method="get" which being sent using URLs you are using method="post" which has a missing attribute action="/action_page.php" that will process you're page.
Like this
<form class="box" action="/action_page.php" method="post">
since you don't have action attribute, and has method="post", the post is being sent to the same page you are sending and without receiving it properly like in php.
$username = $_POST['username'];
If you still want to continue using javascript at test it, remove at post method, and remove the type="submit" on your button as it behaves on submitting if you just want to test using javascript.
Here is your final script.
HTML
<form class="box">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button id="btn" onclick="validate()">login</button>
</form>
</div>
JS
function validate(){
let username = document.getElementById('username').value;
let password=document.getElementById('password').value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have created a html page with a 2 different pages one for login and the other page to show after the successful login.
I have added a proper validation to the login.html page as below:
When I wanted to redirect and open 2nd html page after validating the input fields, I'm unable to open instead the input fields get cleared and the data is shown in the URL.
How can I redirect to the landing.html page which is in the same folder after validating the input fields in the login.html page
function validate(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "username" && password == "user123") {
window.location.href = "landing.html";
} else {
alert("Invalid credentials");
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<div class="container">
<div class="box">
<h1>Login</h1>
<form class="form">
<label>Username</label>
<div>
<i class="fa fa-user"></i>
<input type="text" name="username" id="username" placeholder="Enter Username">
</div>
<label>Password</label>
<div>
<i class="fa fa-lock"></i>
<input type="password" name="password" id="password" placeholder="Enter Password">
</div>
Forgot Password?
<input type="submit" value="Login" onclick="validate()">
</form>
</div>
</div>
You cannot use event.preventDefault unless you assign the event listener to the button or the form event directly
If you have a form, use the submit event!
Why not just change the form action?
Also strongly recommended not to have user id and password in the HTML file
window.addEventListener("DOMContentLoaded", () => {
document.querySelector(".form").addEventListener("submit", function(e) {
const username = this.username.value;
const password = this.password.value;
if (username === "username" && password === "user123") {
this.action = "landing.html";
} else {
e.preventDefault(); // this goes here now
alert("Invalid credentials");
}
})
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<div class="container">
<div class="box">
<h1>Login</h1>
<form class="form">
<label>Username</label>
<div>
<i class="fa fa-user"></i>
<input type="text" name="username" id="username" placeholder="Enter Username">
</div>
<label>Password</label>
<div>
<i class="fa fa-lock"></i>
<input type="password" name="password" id="password" placeholder="Enter Password">
</div>
Forgot Password?
<input type="submit" value="Login">
</form>
</div>
</div>
You've misidentified the problem.
There is no "after validation".
You have onclick="validate()" which calls function validate(event) { passing undefined to the event argument. Then you have event.preventDefault(); which errors because undefined isn't an Event object. The error aborts the function.
Bind your event handlers with addEventListener. It avoids the drawbacks on onclick attributes and will pass an event object to the function.
Note, it is also generally better to listen for a submit event on the form than a click event on the submit button.
document.querySelector('form').addEventListener('submit', validate);
NB: Your approach is completely insecure. You can't give the client the data (the URL) you don't want the user to have until after AuthN is done. They can just look at the source code to see it. AuthN needs to take place on the server.
I have the following validation script that works fine, but I don't understand how it works and need your help with it.
The HTML,
<form action="xyz.php" method="post">
<div class="form-group">
<label class="sr-only" for="id">Enter ID</label>
<input type="text" class="form-control" name="id" id="id" required>
</div>
<button onclick="return validateID()" type="submit" name="submit" class="btn">Submit</button>
</form>
And this is the JS,
<script>
function validateID() {
var id = document.getElementById("id").value;
var regL= new RegExp("^([0-9][0-9][0-9])$");
if (!( (regL.test(id)) )) {
window.location.href = "index-iderror.php";
return false;
} else {
return true;
}
}
</script>
Some questions that I have about this,
What happens when false or true is returned to onclick? Does it decide whether the form data is or is not sent to xyz.php?
How does the execution continue till the line return false after window.location.href? Shouldn't window.location.href direct to a new page stopping execution? The script does not work if return false is removed i.e. the unchecked form data is sent to xyz.php.
I'm having allot of trouble with this and I've tried many different ways to do this and I just ran out of ideas.
Here's my code:
var user = document.Log.User;
var pass = document.Log.Pass;
function Login (){
if(user.value == "Admin"){
window.open();
}
}
Here Is the HTML side:
<form name="Log">
<input class="Log" type="text" name="User">
<input class="Log" type="password" name="Pass">
<input type="button" value="Login" name="But" onclick="Login()" style="width: 70px;position: relative;left: 150px;top: -25px;">
</form>
If your variable assignments are in Javascript that's loaded before the body, then the elements that they refer to don't exist yet, and you should be getting errors. There are a number of ways to fix this:
Put the Javascript in the body somewhere after the form.
Put the Javascript inside window.onload=function() { ... }.
Assign the variables inside the Login() function.
use id Selector an put your variable assignments inside Login function:
HTML :
<form name="Log">
<input id="User" class="Log" type="text" name="User">
<input id="Pass" class="Log" type="password" name="Pass">
<input type="button" value="Login" name="But" onclick="Login()" style="width: 70px;position: relative;left: 150px;top: -25px;">
</form>
JS:
function Login (){
var user = document.getElementById("User");
var pass = document.getElementById("Pass");
if(user.value == "Admin"){
window.open();
}
}
I don't know why you are doing this kind of login logic stuff with js, but, this would work:
function Login (){
var user = document.querySelector('form[name=Log] [name=User]');
var pass = document.querySelector('form[name=Log] [name=Pass]');
if(user.value == "Admin"){
window.open("yoururl.com");
}
}
Hope this helps. Cheers
The alert() works fine, but return false does not stop the form being posted - any ideas?
<script type="text/javascript">
function form_val() {
//Check date
var email=document.getElementById('email').value;
var passw=document.getElementById('password').value;
if(email==''||email==null||passw==''||passw==null) {
alert('Please fill in both fields.');
return false;
}
}
</script>
<form action="userlogin.html" method="post" name="log_form" onsubmit="return form_val();">
<div data-role="fieldcontain">
<input type="email" name="email" id="email" value="" placeholder="Email Address" />
<input type="password" name="password" id="password" value="" placeholder="Password" />
<div class="ui-grid-a">
<div class="ui-block-a">
<button type="submit" name="login" value="" data-theme="c">Sign In</button>
</div>
<div class="ui-block-b">
<br />
Forgotten Password?
</div>
</div>
</form>
You've tagged your question jquery-mobile but you're not using jQuery anywhere in the quoted code.
The code looks right in an old-fashioned DOM0 sort of way (which is okay and should still work except for issues with getElementById on IE7 and earlier). I'd change the checks in form_val a bit:
function form_val(){
//Check date
var email=document.getElementById('email').value;
var passw=document.getElementById('password').value;
if(!email || !passw) {
alert('Please fill in both fields.');
return false;
}
}
...but the ones you had probably should have worked barring the IE issue listed above or other script errors on the page in code that isn't shown.
Here's how you'd use jQuery (which works around the IE bug for you automatically) for the above:
jQuery(function($) {
$("form[name='log_form']").submit(form_val);
});
function form_val() {
if (!$("#email").val() || !$("#password").val()) {
alert('Please fill in both fields.');
return false;
}
}
...or if you don't need form_val to be global (avoid global functions where possible, and it doesn't need to be global just to validate this form):
jQuery(function($) {
$("form[name='log_form']").submit(form_val);
function form_val() {
if (!$("#email").val() || !$("#password").val()) {
alert('Please fill in both fields.');
return false;
}
}
});
You could use a regular "button" type instead of a "submit". Then call your JavaScript onclick to validate and submit the form.