Javascript | Simple Form Validation Wont Work - javascript

I have been working on this really simple login, where all i want to do is say, if the password is "apple" and password is "123" then link me to another page when i click submit button.
I gave up on the submit button linking portion but i still don't understand why my code won't register, everything looks right to me
<!DOCTYPE html>
<html>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="Username" value=""/>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="button" name="submit" value="Login" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var user = document.loginForm.username.value;
return user;
var pass = document.loginForm.password.value;
return pass;
if ( (user=="apple") && (pass=="123") ) {
document.write("It worked");
} else {
document.write("Wrong Password");
}
}
</script>
</body>
</html>

Suggestions:
return keyword will exit the function, so the code after return won't be reached. To remove the two 'return' statement is the first step.
document.write will clear the page after document is loaded. You probably need alert function
try using document.getElementById/getElementByName (which is better) instead of document.loginForm...
It is also better to put onsubmit in the form tag (fired after type=submit button is clicked) instead of onclick event for button.
It is better to put Javascript inside the HTML head tag.
Below is a much better/working version:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
if ( (user=="apple") && (pass=="123") ) {
alert("It worked");
return true;
} else {
alert("Wrong password");
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit='javascript:return validate()'>
<input type="text" id="username" placeholder="Username" value=""/>
<input type="password" id="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
</body>
</html>

Related

open website if "password" is exactly what is needed (github pages)

Sorry if this is a relatively basic question but I'm getting a little bit frustrated, and this is the first time I'm using GitHub Pages
What I want is:
Accept text in form
Compare text in form with password "pass"
if correct, go to a different html site
else, do nothing
thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<form onSubmit="checkPass(this)">
<label>Password:</label>
<input type="text" name="Password" id="pwd" size="20">
<input type="Submit" name="Submit">
</form>
<script>
function checkPass(passForm) {
var password = document.getElementById('pwd');
if (password == "pass"){
windows.open("Website extension here")
}
}
</script>
</body>
</html>
But anyone can view source and open the website right? Everything is right except you missed .value. Add a return false and make windows as window:
function checkPass() {
var password = document.getElementById('pwd').value;
if (password == "pass") {
window.open("https://example.com")
}
}
<form onSubmit="checkPass(); return false;">
<label>Password:</label>
<input type="text" name="Password" id="pwd" size="20">
<input type="Submit" name="Submit">
</form>
The above code will not work in sandbox. So try it using CodeSandbox Demo.

required and button click javascript validation function not work?

I m applying two validation but both are not work
required validatation not work on input attribute
function validatation() not work
signup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="signup.js"></script>
<script type="text/javascript">
function validatation() {
debugger
if (document.PersonalInform.txtfname.value == "") {
debugger
alert("Please provide your first name!");
document.PersonalInform.Name.focus();
return false;
}
}
</script>
</head>
<body>
<form id="txtPersonalInformation" name="PersonalInform" onsubmit="return (validatation());">
<h1>Personal Information</h1>
First Name:<input id="txtfname" name="txtfname" type="text" /><br/>
Middle Name:<input id="txtmname" name="txtmname" type="text" /><br/>
Last Name:<input id="txtlname" name="txtlname" type="text" /><br/>
<input id="btnnext" type="button" value="Next" />
</form>
</body>
</html>
OR
Below Validation Also Not Work
First Name:<input id="txtfname" name="txtfname" type="text" required /><br/>
signup.js
$(document).ready(function () {
$('#btnnext').click(function (event) {
$("#txtPersonalInformation").load("ContactInformation.html");
});
});
I add this line in web.config file
web.config
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
</appSettings>
I want to perform this javascript function validation but not work?
function validatation()
Here's what you want. You weren't submitting you form, as noted by Mendrika.
HTML Form:
<script src="https://code.jquery.com/jquery-3.4.1.min.js"> type="text/javascript"></script>
<form id="some-form" action="some-url" onsubmit="return validate()">
<label for="first-name">First Name:</label>
<input id="first-name" name="first-name" type="text"><br>
<label for="last-name">Last Name:</label>
<input id="last-name" name="last-name" type="text"><br>
<input id="btn-submit" type="submit" value="Submit">
</form>
JS Sample Validate function
function validate() {
if ($("#first-name").val() === "") {
alert("Provide a first name");
$("#first-name").focus();
return false;
}
if ($("#last-name").val() === "") {
alert("Provide a last name");
$("#last-name").focus();
return false;
}
return true;
}
https://codepen.io/el-sa-mu-el/pen/QWjVGvb
Note, this is not good code, but it works. You should read more about basics of JS and form validation.
Some other observations:
Your form is missing the action=" " tag which actually POSTs the data to some URL. Where is your data going?
You are mixing vanilla Java Script and JQuery. Use JQuery for DOM access if you already included it, with the $ symbol.
You have a signup.js function but also include a Javascript function in the <script> tags. You can move the validate() function into the signup.js
Better form validation with JQuery:
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
The reason nothing works is because your form is never submitted.
You just need to change the next button type to submit.
<input id="btnnext" type="submit" value="Next"/>

validating form. addEventListener not listening

OK so I have a form that I check to see if the user enters in a username in the username field. On top of that i also want to know what button what clicked, really im looking to see when the logout button is clicked. It seems to me that the addEventListener isn't registering the 'click' value when the form is submitted. both the buttons and the buttonLength have the right values when I run it with Firefox debugger. So my question is, how do I check the addEventListener value or if its getting passed? looking for some insight on what I'm doing wrong.
<!DOCTYPE html>
<html>
<head>
<title>Not empty</title>
</head>
<body>
<script>
function ValidateForm(frm){
var buttons = document.getElementsByName('adam');
var buttonsLength = buttons.length;
for (var i = 0; i < buttonsLength; i++){
buttons[i].addEventListener('click', clickResponse, false);
};
function clickResponse(){
if(this.id == "logout"){
alert(this.id);
}else {
alert("not logout:" + this.id);
};
};
if (!frm.UserName.value) {
alert("You must enter your username.");
frm.UserName.focus();
return false;
}
return true;
}
</script>
<form method="post" action="test.html" onsubmit="return ValidateForm(this)">
<input type="input" name="UserName" value="">
<input type="password" name="Password" value="">
<button name="adam" id="login">login</button>
<button name="adam" id="sendMe">send me my password</button>
<button name="adam" id="logout">logout</button>
<form>
</body>
Maybe I'm wrong but I think you try to do the following:
<!DOCTYPE html>
<html>
<head>
<title>Not empty</title>
</head>
<body>
<form method="post" name="formname" action="test.html">
<input type="input" id="username" name="userName" value="">
<input type="password" id="password" name="Password" value="">
<button type="button" name="adam" id="login">login</button>
<button type="button" name="adam" id="sendMe">send me my password</button>
<button type="button" name="adam" id="logout">logout</button>
<form>
<script>
var buttons = document.getElementsByName('adam');
var buttonsLength = buttons.length;
for(var i=0;i<buttonsLength; i++){
buttons[i].addEventListener('click', clickResponse, false);
};
function clickResponse(){
var u, p;
u=document.getElementById('username');
p=document.getElementById('password');
switch(this.id) {
case 'logout':
alert('Logout '+this.id);
break;
case 'login':
if(u.value.length==0 ||
p.value.length==0) {
alert("Please enter your unsername and password.");
if(u.length==0) {
u.focus();
} else {
p.focus();
}
} else {
alert('submit');
//document.forms.formname.submit();
}
break;
case 'sendMe':
if(u.value.length==0) {
alert("Please enter your username.");
u.focus();
return false;
} else {
alert('submit');
//document.forms.formname.submit();
}
break;
}
};
</script>
</body>
So, you need to assign listeners before click, then I guessed you want to capture click check button id (command to execute) and then check if user and pass are fullfilled depending the button clicked, if so then submit the form... I've changed your code but I think is what you're looking for.
Hope it helps!!!
Your code is a little messy and hard to understand exactly what you need.
That being said, you should use onclick attributes to bind the buttons to 3 separate functions.
Inside those functions you can get ahold of any dom nodes you need to preform login/logout/sendMe functionality.
Like so:
<!DOCTYPE html>
<html>
<head>
<title>Not empty</title>
</head>
<body>
<script>
function login(){
alert('login function');
// do what you need to here to login
var username = document.getElementsByName('input-username').value;
var password = document.getElementsByName('input-password').value;
if (!username){
alert("You must enter your username.");
}else if (!password){
alert("You must enter your password.");
}
}
function sendMe(){
alert('sendMe function');
// sendMe functionality here
}
function logout(){
alert('logout function');
// logout functionality here
}
</script>
<form method="post" action="test.html">
<input id='input-username' type="input" name="UserName" value="" />
<input id='input-password' type="password" name="Password" value="" />
<button id="login" onClick="login()">login</button>
<button id="sendMe" onClick="sendMe()">send me my password</button>
<button id="logout" onClick="logout()">logout</button>
<form>
</body>

js validation of not null field

I have done a login page. I want my js validateForm()function to alert a user if they have left out the username or password. This is the code I have got at the moment.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("Please enter username");
return false;
}
}
</script>
</head>
<div class="users form">
<br>
<form name="myform" action="Employees/login" onsubmit="return validateForm()" method="post" >
<?php
if (isset($error)) {
echo "<p style='color:red;font-size: 20px''>Username or Password is invalid. Please try again.</p>";
}?>
<p>Enter Username:
<input type="text" name="username" placeholder="username" style="height: 25px;width: 160px;"/></p>
<br><br>
<p>Enter Password:
<input type="password" name="password" placeholder="password" style="height: 25px;width: 160px;"/></p>
<br>
<input type="submit" style="height:35px;width:100px;font-size: 18px; align:center;" value="Sign in">
</form>
</div>
At the moment it is not working, and I think the problem is with the code line "var x=document.forms["myForm"]["username"].value;" Can someone please help?
The issue is forms["myForm"], you used an uppercase F, when actually your form name is all lowercase so it should be:
var x=document.forms["myform"]["username"].value;
// ^ lowercase
Not part of the problem, but you might prefer to use unobtrusive JavaScript to set the onsubmit handler instead of in the HTML attribute:
window.onload = function(){
document.forms["myform"].onsubmit = validateForm;
};
Now, in validateForm you can use this instead of finding the form manually.
function validateForm()
{
var x = this["username"].value;
...
}

Creating a "simple" password validation field

I'm trying to make a password field for a webpage. So far I have:
<form name="PasswordField" action="">
Password:
<input type="password" name="password">
<input type="button" value="Log in">
</form>
Pathetic I know. It doesn't have to be fancy, I just need it to "get" the password from the textbox and match it against the password for the page. I'm assuming I can use an if-else?
*Code for get password from textbox when the "Log in" button is pressed here*
if (password = "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
Sadly I've been fooling with this for hours. I tried functions, too, and that didn't seem to work (for me) either.
If you go that route, you need to put the validation inside a function that gets called in the onclick event of your button. Also to access the password <input node in js, you can give it an id and use document.getElementById(id). Also, = is an assignment operator. Use == for comparison :)
<head>
<script type="text/javascript">
function isValid(){
var password = document.getElementById('password').value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>
<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid();">
</form>
Or an even easier way would be to pass the password DOM node as an argument to the function:
<head>
<script type="text/javascript">
function isValid(myNode){
var password = myNode.value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>
<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid(this);">
</form>
Is this what you are looking for?
document.forms['PasswordField'].elements['password'].value
I used jquery and here's my solution:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input[name='login']").click(function() {
var s = $("input[name='password']").val();
if(s == "rawr") {alert('Correct!')}
else {alert('Wrong Password')}
});
});
</script>
</head>
<body>
<form name="PasswordField" action="">
Password:<input type="password" name="password">
<input type="button" value="Log in" name="login">
</form>
</body>
</html>

Categories