HTML and javascript input and function - javascript

I am a new programer in js and I tried to do a basic website using js and html.
I tried to do like username and password input boxes but the function of it doesn't work. What is the problem?
This is the code:
function entering() {
alert("hi")
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
if (username == "f") {
if (password == "f") {
alert('Nice');
}else {
alert('wrong password');
}else{
alert('wrong username');}}
document.getElementById("frm1").submit();
}
<h1>Best Website</h1>
<h2>Hello!<h2>
<form id = frm1>
Username: <input type = "text" id="fuser"><br>
Password: <input type = "text" id="fpass"><br>
<input type = "button" onclick = "entering()" value = "submit">
</form>

What you are searching for is the value property of the input element.
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
Are only references to the elements in your page, not what the user entered, for that use
var username = document.getElementById("fuser").value;
var password = document.getElementById("fpass").value;
Complete Code:
function entering() {
alert("hi")
var username = document.getElementById("fuser").value;
var password = document.getElementById("fpass").value;
if (username == "f") {
if (password == "f") {
alert("correct");
} else {
alert("wrong password")
}
} else {
alert("wrong username");
}
//document.getElementById("frm1").submit();
}
<h2>Hello!<h2>
<form id = frm1>
Username: <input type = "text" id="fuser"><br>
Password: <input type = "text" id="fpass"><br>
<input type = "button" onclick = "entering()" value = "submit">
</form>

var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
When grabbing an input element, you get the element stored into a variable, not the value. When you write your if conditional then, you need to point to the property on the element called value.
if (username.value == "f") {
if (password.value == "f") {

You'll need to rework your if/else statements and make sure to access the value of the element you're referencing.
if (username == "f") {
if (password == "f") {
alert('Nice');
}else {
alert('wrong password');
}else{
alert('wrong username');}}
To:
if (username.value == "f") {
if (password.value == "f") {
alert('Nice');
} else {
alert('wrong password');
}
} else {
alert('wrong username');
}
That should get you moving again.
<!DOCTYPE html>
<html>
<head>
<title>The Best Website</title>
</head>
<body>
<h1>Best Website</h1>
<h2>Hello!
<h2>
<form id=frm1>
Username:
<input type="text" id="fuser">
<br> Password:
<input type="text" id="fpass">
<br>
<input type="button" onclick="entering()" value="submit">
</form>
<script>
function entering() {
alert("hi")
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
if (username == "f") {
if (password == "f") {
alert('Nice');
} else {
alert('wrong password');
}
} else {
alert('wrong username');
}
document.getElementById("frm1").submit();
}
</script>
</body>

Related

The Verification between email addresses function will not work

I want the user to verify his email address in the "email2" field and in case he has entered the wrong email address the function returns an error message and corrects his email address from the "email" field. This function returns no error but also does not work, ie does not report an error message when email addresses differ. I'm asking for help.
<html>
<script>
function validateForm() {
var x = document.forms["contactform"]["email"].value;
if (x == "") {
alert("E-mail is empty");
return false;
}
var x = document.forms["contactform"]["email2"].value;
if (x == "") {
alert("Verification E-mail is empty");
return false;
if(email != email2){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
}
}
</script>
<body>
<form name="contactform" method="post">
<input type="text" name="email" maxlength="80" size="30" placeholder="E-mail contact person" title="The e-mail must be in the format, example: primer#email.com ">
<input type="text" name="email2" maxlength="80" size="30" placeholder="Verify E-mail address" title="The e-mail must be in the format, example: primer#email.com ">
<input type="submit" value="Send" style="border:1px solid #000000">
</form>
</body>
</html>
You are missing a } to terminate the second IF so the third IF is inside the second and therefore never runs because it is after a return :)
<script>
function validateForm() {
var x = document.forms["contactform"]["email"].value;
if (x == "") {
alert("E-mail is empty");
return false;
}
var x = document.forms["contactform"]["email2"].value;
if (x == "") {
alert("Verification E-mail is empty");
return false;
} <-- !!!!!!!!!!!!! THIS WAS MISSING !!!!!!!!!!!!
if(email != email2){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
#} <-- THIS WAS IN THE WRONG PLACE REMOVE IT
}
</script>
You defined a variable named x to hold email input values, then you do comparison with email and email2 variable, which are not defined.
function validateForm() {
var email = document.forms["contactform"]["email"].value;
if (email == "") {
alert("E-mail is empty");
return false;
}
var verificationEmail = document.forms["contactform"]["email2"].value;
if (verificationEmail == "") {
alert("Verification E-mail is empty");
return false;
} <-- !!!!!!!!!!!!! THIS WAS MISSING !!!!!!!!!!!!
if(email != verificationEmail){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
}

if/else not working in Javascript Login Page

I have created a Login Page with HTML, CSS & JS. If the value in <input> is correct, the js code takes me to the location I want with the code window.location.replace("href") and if the value is incorrect, it displays an alert.
But I want a code so that if the input is empty it would show another alert not the previous one. I have also used required field in html <input> tag: <input type="password" id="password" class="input" required>, but by using required the whole code doesn't works.
The code is:
Javascript
function auth(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} else {
alert("Please enter valid information");
return;
}
}
I have tried this but it is not working:
`
function auth(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} else {
alert("Please enter valid information");
return;
}
if (username === "" && password === "") {
alert("Please enter information");
} else {
return;
}
}
`
The problem is with your if/else structure.By using required in form, your form is not submitted and your function is not called, your function will only be called when the form is submitted, required doesn't allow form to submit until the field is filled out.
html file is:
<body>
<form id="form">
<input type="text" placeholder="username" id="username">
<input type="text" placeholder="password" id="password">
<button type="submit">Submit</button>
</form>
<script src="index.js"></script>
</body>
and javascript file will be:
document.getElementById("form").addEventListener("submit", auth);
function auth(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
console.log(username);
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} if (username === "" && password === "") {
alert("Please enter information");
} else{
alert("Please enter valid information");
return;
}
}
for live demo, visit my codepen
Just add a validation to check if the fields are empty:
if (username.length === 0 || password.length === 0) {
alert("Username and password must be filled!");
return;
}
So your method would look like:
function auth(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
// check if the username of password are empty
if (username.length === 0 || password.length === 0) {
alert("Username and password must be filled!");
return false;
}
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} else {
alert("Please enter valid information");
return;
}
}
Regarding your second snippet, you cant do 2 else's like if / else / else, the right way to do it with a single if block would be to use a simple, if / else if / else like this:
function auth(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username.length === 0 || password.length === 0) {
alert("Username and password must be filled!");
return;
} else if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} else {
alert("Please enter valid information");
return;
}
}
NOTE: Javascript code can be seen just by inspecting the code of the page, so storing username & password in the js file like you are doing is super insecure, anyone would be able to inspect the code and see what username and password should be used.
The reason I can see is the order of if-else and if statements. The if statement after if-else is unreachable that's why it does not show the new alert you added.
Try using the following code :
function auth(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "admin#gmail.com" && password === "user")
{
window.location.replace("http://www.rex14.ml/");
} else if (username === "" && password === "") {
alert("Please enter information");
} else {
alert("Please enter valid information");
return;
}
}
Fist of all, you should use "else if". Otherwise your third condition would never be considered. A simple solution is like this:
function auth(event) {
event.preventDefault();
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} else if (username === "" && password === "") {
alert("Please enter information");
return;
} else {
alert("Please enter valid information");
return;
}
}
You can also get rid of any "else" statement this way:
function auth(event) {
event.preventDefault();
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
return;
}
if (username === "" && password === "") {
alert("Please enter information");
return;
}
alert("Please enter valid information");
return;
}
Second, if you have a "required" input inside a form, and you leave it empty, it won't be submitted. If your input is not inside a form, add an event handler. If it is inside a form, remove the "required" field because you are already handling the empty input problem inside your auth function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="form" onsubmit="return auth(this)">
<input type="text" placeholder="username" id="username" />
<input type="text" placeholder="password" id="password" />
<button type="submit">Submit</button>
</form>
</body>
<script>
function auth(event) {
var username = event.username.value;
var password = event.password.value;
if (username === "admin#gmail.com" && password === "user") {
window.location.replace("http://www.rex14.ml/");
} else {
alert("Please enter valid information");
return false;
}
return false;
}
</script>
</html>

Form validation not working

I have a simple log in and I cannot get the validation to work at all. I was wondering if someone could help.
HTML:
<div class="login">
<h2>Sign In</h2>
<form id="frmLogin" method="post">
Username: <input id="txtUsername" name="txtUsername" type="text" /><br/>
Password: <input name="txtPassword" type="password" /> <br/>
<button onClick="validateLogin()">Log In</button>
</form>
</div><!-- End of Login Section -->
Javascript:
<script>
function validateLogin()
{
var userName = document.getElementsByID('txtUsername').value;
var invalidForm = 0;
if(userName == "")
{
alert("Username cannot be blank!");
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}//end if
}
</script>
At the moment I'm just testing for an empty username, once I can get this working I'll continue on with the rest.
Thank you!
To get and element by ID the function name is getElementById and not getElementsByID, besides, javascript is case sensitive so getElementByID does not work.
function validateLogin()
{
var userName = document.getElementById('txtUsername').value;
var invalidForm = 0;
if(userName == "")
{
alert("Username cannot be blank!");
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}//end if
}
Do your jquery code something like these :-
<script>
function validateLogin()
{
var userName = document.getElementById('txtUsername').value;
var invalidForm = 0;
var errMessage = ""
if(userName === "")
{
errMessage = "Username cannot be blank!";
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}
else if (invalidForm == 1)
{
alert(errMessage);
return false;
}
}
</script>
It may help you.

Email validation Jquery not working

I have been working on a simple email validation. But it doesn't work.
Any ideas why it isn't working? Am I doing something wrong or should I structure my code in some other way?
I have done a function like this:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
} else {
return true;
}
}
and after that I'm calling that function in my setupRegistration function.
My JS looks like this:
function doOutputMessage(type, message){
$("#outputMessage").html("");
$("#outputMessage").removeClass();
$("#outputMessage").hide();
if(type == "error") {
$("#outputMessage").addClass("error").fadeIn("fast");
} else if(type == "success") {
$("#outputMessage").addClass("success").fadeIn("fast");
}
$("#outputMessage").text(message);
$("#outputMessage").show();
}
function setupRegistration(){
$("#signupWrapper").on("click", "#regUser", function(){
var username = $("input[name='username']").val();
var email = $("input[type='email']").val();
var password = $("input[type='password']").val();
if(username == ""){
doOutputMessage("error", "Fill in your desired username!");
}
if(email == ""){
doOutputMessage("error", "Fill in your email!");
}
if(IsEmail(email)==false){
doOutputMessage("error", "mailen är fel förfan");
}
if(password == ""){
doOutputMessage("error", "Fill in your desired password!");
}
if(username != "" && email != "" && password != ""){
ajaxCall(username, email, password);
}
});
}
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
function ajaxCall(username, email, password){
$.ajax({
type: 'POST',
url: '../register.php',
data: {
'username' : username,
'email' : email,
'password' : password,
},
success: function(data) {
if(data.exists){
doOutputMessage("error","That Username is allready taken.");
} else if(data.inserted) {
doOutputMessage("success","You have successfully been registered!");
}else {
doOutputMessage("error","Something went wrong, try again later.");
}
}
});
}
$(document).ready(function(){
setupRegistration();
});
function regSubmit(){
clearErrorMessages();
var username = $("#regForm #username").val();
var email = $("#regForm #email").val();
var password = $("#regForm #password").val();
if(username == ""){
showValidationMessage("#regForm #error_username", "Fill in your desired username!");
}
if(email == ""){
showValidationMessage("#regForm #error_email", "Fill in your email!");
}
if(password == ""){
showValidationMessage("#regForm #error_password", "Fill in your desired password!");
}
if(username != "" && email != "" && password != ""){
$.ajax({
url: 'regLogin.code.php',
type: 'POST',
data: {
'action' : 'register',
'username' : username,
'email' : email,
'password' : password
},
success: function(data, status){
console.log(data);
if(data == "exist"){
showValidationMessage("#regForm #error_general", "A user with that username or password already exists!");
}else if(data == "illegal"){
showValidationMessage("#regForm #error_general", "Your username contains illegal characters!");
}
else if(data == "true"){
showValidationMessage("#regForm #success", "Success!");
setTimeout(function(){
window.location.replace("/admin/inside/");
}, 1000);
}
},
error: function(xhr, desc, err){
showValidationMessage("#regForm #error_general", "Something went wrong, please try again");
}
});
}
}
#Mario-Chueca is right. Your code is mostly working correctly, however, you are making an Ajax call regardless if the email is correct and as a result the error message is not shown. You should only make the ajax call when the specified email is valid:
if(username != "" && email != "" && password != "" && IsEmail(email)){
ajaxCall(username, email, password);
}
I have included a code sample below to show that your email validation (without Ajax call) is working. I have included the if(!IsEmail(email){ fix suggested by #Abdulla and I also also added a more complex regular expression from this post.
function IsEmail(email) {
//var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//More advanced regex to valid 99.99% of most emails in use, see https://stackoverflow.com/questions/46155/validate-email-address-in-javascript
var regex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if (!regex.test(email)) {
return false;
} else {
return true;
}
}
function doOutputMessage(type, message) {
$("#outputMessage").html("");
$("#outputMessage").removeClass();
$("#outputMessage").hide();
if (type == "error") {
$("#outputMessage").addClass("error").fadeIn("fast");
} else if (type == "success") {
$("#outputMessage").addClass("success").fadeIn("fast");
}
$("#outputMessage").text(message);
$("#outputMessage").show();
}
//if (IsEmail('john.doe#stackoverflow.com')) {
// doOutputMessage('success', 'valid email')
//}
if (!IsEmail('john.doe#stackoverflow.com')) {
doOutputMessage('error', 'invalid email')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outputMessage">Test</div>
Use some of the advices from before, but change this too, the error doesn't stop the ajax call:
var error_email=false;
if(!IsEmail(email)){
error_email=true;
doOutputMessage("error", "mailen är fel förfan");
}
if(password == ""){
doOutputMessage("error", "Fill in your desired password!");
}
if(username != "" && email != "" && password != "" && !error_email){
ajaxCall(username, email, password);
}
remove false in here
if(!IsEmail(email){
and regex should be
regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
Live DEMO
How to Find or Validate an Email Address
please try:
function IsEmail(email){
var reg = /^[a-zA-Z0-9\.\-\+]+\#([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/
return reg.test(email)
}

username and password validation using javascript

I have this simple problem that I don't know what did I do wrong.
so I have this code:
function validateForm()
{
var validation = true;
validation &= validateUsername();
validation &= validatePassword();
return validation? true:false;
}
function validateUsername()
{
var username = $('#username').val();
if( username == "" )
{
alert("Login failed, Please enter your username");
return false;
}
else if( username != "username" )
{
alert("Login failed, Username Incorrect");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var password = $('#pass').val();
if(password != "password")
{
alert("Login failed, Password is incorrect");
return false;
}
else if(password == "")
{
alert("Login failed, Please enter your password");
return false;
}
else
{
return true;
}
}
If I enter no password it should alert that you should enter your password but instead that it is alerting password is incorrect. Why is it not going through all the if's I created?
You swap the conditions, and check for an empty string before you check for the correct password
function validatePassword() {
var password = $('#pass').val();
if(password == "") {
alert("Login failed, Please enter your password");
return false;
} else if(password != "password") {
alert("Login failed, Password is incorrect");
return false;
} else {
return true;
}
}
right now you're checking if it's not the correct password first, and as an empty string probably isn't the correct password, that matches before the check for an empty string.

Categories

Resources