I'm trying to validate my form so that if the user doesn't enter the username or the password, he isn't allowed to login to the website. For some reason, when I do enter both the username and password fields, and click login, the login.html page doesn't appear. Any help?
<script>
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
<form id="loginform" name="loginform" method="post">
<div>
<label hidden> Username</label>
<input type= "text" class="text" placeholder="Username" title="Username" name="username">
<span id="usernameError"></span>
<label hidden> Password </label>
<input type= "password" class="text" placeholder="Password" title="Password" name="password">
<span id="passwordError"></span>
Forgot password?
</div>
<div class="button-container">
<a href="login.html" target="_blank"> <input type= "submit" value="Login" class="login"/>
</a>
<input type= "button" value="Sign up" class="login signup"/>
</div>
</form>
You had your submit button wrapped in an a element that was pointing to login.html, which is not how to properly redirect after a form submission. This will also cause problems with handling events because of event bubbling and/or capturing.
In actuality, you haven't specified where the form should send its data to in your form tag:
<form id="loginform" name="loginform" method="post">
Which (by default) means that the form will send its data to the current page (causing the same page to reload, but have the form data accessible to it in this updated load).
To send the data to a different page/resource, the form needs to have an action attribute which specifies the path to the destination:
<form id="loginform" name="loginform" method="post" action="login.html">
See this for details on submitting forms.
Stack Overflow's code snippet environment doesn't allow for form submissions, but check out this Fiddle which has an updated version of your code that works.
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 a reset password form. After submitting it, it redirects to login page. However, it doesn't show any success message upon getting the successful reset password. And, I'm uncertain how can I do this as these are two different jsp files. And even if the login page uses the reset password javascript code, it still can't be able to show the conditional message. I am using java spring boot, jquery and javascript. This is my code:
resetPassword.js
$(".resetPassword").on('submit', function (e) {
e.preventDefault();
var password = $("#pass").val();
var confirmPass = $("#confirmPass").val();
if(password !== confirmPassword){
$(".perror").show();
}
else {
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
});
resetPassword.jsp
<form:form action="/reset_password" method="POST" class="resetPass" modelAttribute="resetPassword">
<div class="alert alert-danger perror" role="alert" style="display: none">Password not match</div>
<form:input type="hidden" path="token" />
<div class="form-group-row ">
<label htmlFor="passwordReset">Password</label>
<input type="password" id="pass" path="password" placeholder="Password" required/>
</div>
<div class="form-group-row ">
<label htmlFor="confirmPasswordReset">Confirm Password</label>
<input type="password" id="confirmPass" placeholder="Confirm Password" required/>
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form:form>
Now, this is the login.jsp in where I want the successful message which currently now I've been showing from alert box however that seems not a good design.
login.jsp
<form:form action="/login" method="POST" modelAttribute="user" >
<div class="alert alert-success successfulResetPassword" role="alert" style="display: none>Your password changed successfully. Please login using your email and password</div>
<input type="text" id="email" name="email" placeholder="email" required/>
<input type="password" id="password" name="password" placeholder="pass" required/>
</form:form>
now all I want, is to show the div class=successfulResetPassword after a user reset the password show that the display alter it's value to visible. But I haven't found any good way to this as reset password is using a different js file and from that submit button I'm redirected the whole scenario to login page. Even if the login page can access that js page still it can't have the value of changing display property :
$("#successfulResetPassword").show();. I tried to modify my code like this till now :
resetPassword.js
else {
$("#successfulResetPassword").show(); //it could've shown the msg, but can't because it's in button submit condition after redirected to login page which has no **resetPassword** class
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
And this is my backend code:
#PostMapping("/reset_password")
public String resetPasswordSubmit(Map<String, Object> model, #ModelAttribute("resetPassword") ResetPasswordDTO resetPassword){
model.put("pageTitle", Constant.PAGE_TITLE);
GenericResponse response = loginService.changePassword(resetPassword);
if(response.getStatusCode() == 200){
return "redirect:/login";
}
model.put("error", "error");
return "resetPassword";
}
I want to set hidden input value(username) based on client other input(email) in a form, then submit to server. (to make sure username equal to email)
However, the assignment to the hidden input is processed AFTER the form submitted. So 'username' is already None on server side.
<form id="altForm" action="" method="post">
<input type="hidden" name="username" id="id_username" maxlength="40" >
<input type="email" name="email" id="id_email" maxlength="40">
<input class="btn btn-primary pull-right" type="submit" value="Register" />
</form>
<script>
$("#altForm").submit(function(e){
e.preventDefault();
var username = $("#id_email").val();
$("#id_username").val(username);
});
</script>
I would do this serverside, but if you want it clientside you can also accomplish it like this:
$('#id_email').keyup(function() {
$('#id_username').val($(this).val());
});
This code runs smoothly except submit function. If I change the submit function with another function such as "show();" it works. Why doesn't it run this submit function?
$(document).ready(function() {
$('#submit').click(function() {
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if (email == "" || password == "") {
$('.division').show();
} else {
$('#form').submit();
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" method="post" action="run.php">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" id="submit" value="Sign in" onClick="return false;">
</form>
The problem is that you've given your submit button the id "submit". Browsers add elements to the form object using the id, so the normal submit function of the form is being replaced with a reference to your submit button.
Change the name (and probably id) of the submit button to (say) submit-btn and it will work. Live Example
Separately from that, though, I wouldn't hook click on the submit button at all; I'd hook submit on the form element, since forms can be submitted in other ways (pressing Enter in certain form fields, for instance).
Example: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
$(document).ready(function(){
$('#form').submit(function(e){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if( email == "" || password == "") {
$('.division').show();
e.preventDefault(); // Don't allow the form submission
}else{
$('#form').submit();
}
})
});
</script>
<!-- Using GET rather than POST, and no action
attribute, so that it posts back to the jsbin page -->
<form id="form" method="get">
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="checkbox" checked="checked" id="keep" value="yes">
<label for="keep">Keep login</label>
<input type="submit" value="Sign in">
</form>
<div class="division" style="display: none">Please fill in an email and password</div>
</body>
</html>
In your input element, you have onClick="return false;"This onClick function is being given priority over the click handler that you defined in jQuery. If you remove the onClick portion of your input element, your jQuery code will run.
Aside, there is a problem with your submit code in that it never actually prevents the POST to the server. See my edit below:
if( email == "" || password == "") {
$('.division').show();
return false;
}else{
('#form').submit();
}
You must explicitly return false to prevent the form from submitting to the server. Alternatively, you can just remove the else clause altogether, due to the fact that if the function doesn't explicitly return false, it will complete and continue with the form submission.
Also note that for form submissions, it is typically better to use the onSubmit event as opposed to the onClick event, since forms can technically be submitted by hitting the 'enter' key as well as clicking the submit button. When onClick is used, the submission is not triggered via hitting the enter key.