HTML Form button press twice to open new page - javascript

I want to make a simple login using form, i create a form that has input field for user to key in password and then the user press submit button
the password will be retrieved using javascrip, if the password is correct it will open a new page
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.password.value == "nopassword")
{
self.location='main.html'
}
else
{
alert("Wrong Password\nTry again Bak Choy Friend! :)")/*displays error message*/
}
}
</script>
.
.
.
<form>
<input type="text" placeholder="Password" name="password">
<input type="button" class="button" value="Login" onclick="check(this.form)"/>
</form>
But the problem is it requires the user to press twice instead of one before it can open a new page?
the first time, i press the button with the password, the address bar displays
...net/?password=nopassword
then, the 2nd time i press the button with the password, it will redirect me to the new page
may i know how can i solve this problem?

Try this :
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.password.value === "nopassword")
{
self.location = 'main.html';
return true;
}
else
{
alert("Wrong Password\nTry again Bak Choy Friend! :)")/*displays error message*/
return false;
}
}
</script>
<input type="button" class="button" value="Login" onclick="return check(this.form);"/>

Related

Simple Login Form

I am trying to implement a simple login form using JavaScript and HTML. When I submit the form, I want to check the username and password against a list of valid credentials.
If the credentials are valid, I want to redirect the user to the home page. Otherwise, I want to show an error message. I have written the following code, but it is not working as expected. Can someone please help me debug this issue?
<form id="login-form">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('login-form');
const username = document.getElementById('username');
const password = document.getElementById('password');
form.addEventListener('submit', function(event) {
event.preventDefault();
const validCredentials = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' }
];
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
window.location.href = '/home';
} else {
alert('Invalid username or password');
}
}
});
</script>
I am implement a simple login form using JavaScript and HTML.
The expected outcome of the code is that when the user enters a valid username and password and clicks the submit button, they will be redirected to the home page. If the username and password are invalid, an error message should be displayed.
First of all, don't do this if you want to use this code for real users and production web app. It's not a good approach to hardcore users or passwords in a JavaScript script. If you are using this code for learning purposes, it's okay!
Secondly, the code has two meaningful problems. The alert inside the else block is running after every iteration of the for loop. You have to add a return statement to stop the loop and exists the function. Place the alert after the for loop, because the intention of the alert (I guess) is: if you don't find any coincidence, show to the user that the username and password are invalid.
for (const credential of validCredentials) {
if (credential.username === username.value && credential.password === password.value) {
return window.location.href = '/home';
}
} //end of the loop
alert('Invalid username or password');
}); //end of the callback function
});
On the other hand, in window.location.href = '/home', the string is a malformed URI. You have to send user to a completed URI like, https://google.com/ or http:/yoursite.com/home

Javascript change password by using an input

I am new in Javascript and I want to make a code where a window will be open asking the user to type a specific password. If the password is correct then he "enters" the page. In the page, he can find an input and a button. He can change the password by filling the input and then pressing the Submit button. Basically to change the value of the variable. The problem is that I don't know how can I "pass" the input with id="changePass" to the variable pass1 and then I am not sure if the new password will be saved. Thank you in advance! Bellow you can find my code:
<html>
<body>
<script>
var entered = false;
var password;
var pass1="pass";
if (entered == false) {
password = prompt('Enter your password in order to view this page!', ' ');
if (password == pass1) {
alert('Correct Password, Enter the Club');
entered = true;
} else {
window.location = "";
}
} else if (entered == true) {
alert('You have already entered the password. Click OK to enter!');
}
</script>
<input id="changePass"/>
<button id="subimt" type"Submit">Submit</button>
</body>
</html>
My friend you can't rely on browser storage and cookies for logging in users and keeping passwords. The least of your problems is that if a user clears his cookies and history you are going to lose it all. :)
This is why I asked if it is a homework or at least something that you don't really care to hold on to user credentials, and your users won't have any problem to re-enter the default password every once a while.
With that being said below is the code you want to store the password to local storage
<input id="changePass"/>
<button id="changePassBtn" type"Button" onclick='changePassBtnClick()'>Change Password</button>
<input id="login"/>
<button id="loginBtn" type"Button" onclick='loginBtnClick()'>Login</button>
<script>
if(!localStorage.getItem('password')){
localStorage.setItem('password', 'pass');
}
function changePassBtnClick(){
localStorage.setItem('password', document.getElementById('changePass').value);
alert('Password changed');
}
function loginBtnClick(){
if(document.getElementById('login').value == localStorage.getItem('password')){
alert('Correct Login');
}else{
alert('Wrong Password');
}
}
</script>

How to submit a form with JavaScript using python Requests?

I have a page as follows.
www.pict.ethdigitalcampus.com
I wish to submit the form data on this page using python Requests.
But unfortunately on this website, when the Submit button is clicked it calls a validate function.
<input type="submit" value="Sign In" onclick="return validate();" style="font-family: Verdana">
Now this validate function actually encrypts the password using some algorithm and then submits it to the server.
This is how the validate function works:
function validate()
{
if(isBlank(document.loginForm.loginid.value) || isNull(document.loginForm.loginid.value))
{
alert('Please Enter Login Id.');
document.loginForm.loginid.focus();
return false;
}
if(isBlank(document.loginForm.password.value) || isNull(document.loginForm.password.value))
{
alert('Please Enter Password.');
document.loginForm.password.focus();
return false;
}
var hashObj = new jsSHA("mySuperPassword", "ASCII");
var password = hashObj.getHash("SHA-512", "HEX");
var textval =document.loginForm.password.value; //The actual password entered by the user
var encryptedString = $.jCryption.encrypt(textval, password); //The password is encrypted and stored
document.loginForm.password.value = encryptedString; //The password field of the form is updated with "encrypedString"
document.loginForm.hiddenfield.value=password;
document.loginForm.service_id.value=get_cookie(document.loginForm.loginid.value.toUpperCase());
document.loginForm.action="http://pict.ethdigitalcampus.com:80/DCWeb/authenticate.do";
return true;
}
Now since I cannot directly submit form data to the action page, I have no choice but to click that button and execute this JavaScript function.
I have tried using urllib and still no luck. What do I do?

Keep input value after form submit (with a catch)

In PHP, if the text input "cmtx_comment" is empty, on form submit I show a javascript alert. After I press OK in the alert, the values entered by the user in all fields in the form are gone. How can I keep the user entered values, without adding code to the value of the input elements (something like <input type="text" name="something" value="<?php echo $_GET['something'];?>"> ?
if (empty($cmtx_comment)) { //if comment value is empty
echo <<<EOD
<script>
alert('Please enter a comment!');
</script>
EOD;
return false;
} else { //if comment entered
do stuff
Have you tried localStorage and form validation?
HTML:
<form method="post" action="" onSubmit="return saveComment();">
<input type="text" name="cmtx_comment" id="cmtx_comment" value="" />
<input type="submit" value="Save" />
</form>
JavaScript:
document.getElementById("cmtx_comment").value = localStorage.getItem("comment");
function saveComment() {
var comment = document.getElementById("cmtx_comment").value;
if (comment == "") {
alert("Please enter a comment in first!");
return false;
}
localStorage.setItem("comment", comment);
alert("Your comment has been saved!");
location.reload();
return false;
//return true;
}
Example
On first page load, you are presented with:
If you don't enter a comment, you get the alert:
If you do enter a comment, you get a different alert:
The page will then refresh (or post, simply un-comment the return true, and comment the location.reload), and you will still see the contents you posted the first time.

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