input type password is immovable - javascript

I have this code and the 1st input won't ever move whatever I do the only thing that made it move was float:right; but I don't want it to be like this I even created this div->P so maybe it would move. Has anyone encountered this problem before?
Is it possibly interfearing with my js? That's the only thing I can think of rn
.inner {
display:inline-block;
margin-right:500px;
}
.pswd {
display:inline-block;
margin-right:500px;
}
</style>
</head>
<body>
<div class="P">
<input class="inner" type="password" id="pswd">
<input class="inner" type="button" value="Submit" onclick="checkPswd();"/>
</div>
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "admin";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="A.html";
}
else{
alert("Password incorrect.");
}
}
</script>

This should work if you use the ID selector rather than the class selector (i.e. use # rather than .):
#pswd {
display:inline-block;
margin-right:500px;
}

There are multiple ways to center-align a div both vertically and horizontally on the screen.
I have used display:flex for the same.
'use-strict'
function checkPswd(form) {
const confirmPassword = "admin";
let passwordProvided = form.elements.newPassword.value;
if (passwordProvided === confirmPassword) {
// If correct
} else {
// If failure
}
// to prevent default action
return false;
}
.form--wrapper {
width: 150px;
height: 150px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
form {
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
width: 100%;
border: 2px dashed orange
}
<div class="form--wrapper">
<form name="change-password" onsubmit="return checkPswd(this)">
<input class="inner" name="newPassword" type="password">
<input class="inner" type="submit" value="Submit" />
</form>
</div>

Related

Enter the prototype of an Object.prototype.function(), where all the EventListeners are safed (Javascript)

I am working on an assignment, that constructs a small library. The project requires, that the user can input the title of a book, its author, number of pages and if the user has already read it. Then the content gets displayed on the page.
Here's the code (work in progress):
let myLibrary = [];
let submitBtn = document.querySelector("#submitBtn");
let textInput = document.querySelectorAll("input");
let addNew = document.getElementById("addNew");
let fieldSet = document.getElementById("fieldset");
let cancelBtn = document.querySelector("#cancelBtn");
let bookDisplay = document.getElementById("bookDisplay");
let flexItems = document.getElementsByClassName("flexItems");
// object Constructor for new books
class Book {
constructor(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
}
Book.prototype.addToDisplay = function() {
let newDiv = document.createElement("div");
bookDisplay.appendChild(newDiv).className = "flexItems";
let newSpan = document.createElement("span");
flexItems[myLibrary.length-1].appendChild(newSpan).className = "spanItem";
newSpan.innerText = this.title;
this.read === true ? flexItems[myLibrary.length-1].style.backgroundColor = "green" :
flexItems[myLibrary.length-1].style.backgroundColor = "red";
newDiv.addEventListener("mouseenter", moreInfo => {
newSpan.childNodes[0].nodeValue = this.author + "\n" + this.title + "\n" + this.pages + " pages";
})
newDiv.addEventListener("mouseleave", defaultInfo => {
newSpan.childNodes[0].nodeValue = this.title;
})
}
// creates a new instance of Book and pushes the object into the array
let addToLibrary = function addToLibrary() {
newBook = new Book(textInput[0].value, textInput[1].value, textInput[2].value, textInput[3].checked)
myLibrary.push(newBook);
newBook.addToDisplay();
};
// eventlistener, to submit a new Book to the library
submitBtn.addEventListener("click", addToLibrary);
// sets the form's display from block to non-visible
let cancel = function cancel() {
fieldSet.style.display = "none";
}
// cancels the form and returns back
cancelBtn.addEventListener("click", cancel);
// sets the form's display from non-visible to visible
let openForm = function openForm() {
fieldSet.style.display = "block";
}
// opens form to add new book
addNew.addEventListener("click", openForm);
body {
margin-left: 20px;
}
h1 {
text-align: center;
}
#fieldset {
position: fixed;
z-index: 2;
border: none;
display: none;
background: #3CBC8D;
border-radius: 10px;
right: 1%;
top: 2%;
width: 400px;
height: auto;
overflow: auto;
}
button {
cursor: pointer;
}
.display {
display: flex;
flex-direction: row;
flex-wrap: wrap;
position: relative;
}
.flexItems {
position: relative;
display: flex;
margin: 5px;
color: black;
font: Georgia;
font-size: 20px;
height: 200px;
width: 200px;
align-items: center;
border: 2px solid gray;
transition: 500ms;
border-radius: 5px;
}
.spanItem {
width: 100%;
text-align: center;
white-space: wrap;
overflow: hidden;
text-overflow: ellipsis;
}
.display .flexItems:focus,
.display .flexItems:hover {
transform: scale(1.2);
z-index: 1;
}
#addNew {
position: fixed;
z-index: 2;
border: none;
background: #3CBC8D;
color: white;
border-radius: 10px;
right: 2%;
top: 2%;
width: 100px;
height: 50px;
overflow: auto;
cursor: pointer;
}
/*. Could be additionally used for the hover-effect, but doesnt look that nice for more than one row
flexItems:hover ~.flexItems {
transform: translateX(25%);
}
.display:focus-within .flexItems,
.display:hover .flexItems {
transform: translateX(-25%);
}
.flexItems:focus ~.flexItems,
.flexItems:hover ~.flexItems {
transform: translateX(25%);
} */
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
<title>Library</title>
</head>
<body>
<div><h1>My book library</h1></div>
<div id="bookDisplay" class="display">
</div>
<div>
<button id="addNew">Test</button>
</div>
<fieldset id="fieldset">
<form id="form">
<div>
<label for="title">Title: </label>
<input type="text" name="title" id="title" class="usrInput">
</div>
<div>
<label for="author">Author: </label>
<input type="text" name="author" id="author" class="usrInput">
</div>
<div>
<label for="number">Number of pages: </label>
<input type="number" name="number" id="number" class="usrInput">
</div>
<div>
<label for="read">Already read?: </label><br>
Y <input type="radio" name="read" id="read" value="Y" class="read">
N <input type="radio" name="read" id="read" value="N" class="read">
</div>
<button id="submitBtn" type="button">Submit</button>
<button id="cancelBtn" type="button">Cancel</button>
</fieldset>
</div>
</body>
</html>
**My question: ** The code is working until here. But I have my concerns with the mouseenter-Eventlistener. On mouseenter, I want to add a <button>, to edit the book's value. And maybe there is moreto be added in the future. That would mean the àddToDisplay() function eventually will get clunky. So I was wondering, if I could enter the Object.prototype of the addToDisplay() function and store all eventListeners in its prototype. Is this possible in Javascript?
The only way I could solve it right now is, to write an extra function for the eventlisteners. But it seems, that this way, I'm just going back to normal function expressions with dozens of values to pass by:
Book.prototype.addToDisplay = function() {
// (...)
mousehover(this, newDiv, newSpan)
}
let mousehover = function mousehover(test, newDiv, newSpan) {
newDiv.addEventListener("mouseenter", moreInfo => {
newSpan.childNodes[0].nodeValue = test.author + "\n" + test.title + "\n" + test.pages + " pages";
})
newDiv.addEventListener("mouseleave", defaultInfo => {
newSpan.childNodes[0].nodeValue = test.title;
})
}
Hope I got the problem across. It's the first assignment to Objects I'm working on.
Thanks for any answers and links to informative sources.

using local storage with javascript

I have a signup form that saves user data. The data doesn't save to local storage when it is supposed to. The app is supposed to sign up a user and save the data to the local storage, if someone attempts to sign up with already existing username, the app prevents the user from doing that.
the javascript file does the following
1) prevents users from signing up with already existing username
2) saves an object to the local storage which is passed into an array
var signUpBtn = document.querySelector('#signUp');
var signUpOver = document.querySelector('.signup__overlay');
var signInBtn = document.querySelector('#signIn');
var signInOver = document.querySelector('.signin__overlay');
var fullname = document.querySelector('#name');
var email = document.querySelector('#email');
var password = document.querySelector('#password');
var age = document.querySelector('#age');
var occupation = document.querySelector('#occupation');
var Address = document.querySelector('#address');
var signupSubmitClicked = document.querySelector('#signupClicked');
signupSubmitClicked.addEventListener('click', () => {
if (fullname.value=="" || email.value=="" || password.value=="" || age.value=="" || occupation.value=="" || Address.value=="") {
alert("incomplete datails, please fill up everything")
} else {
alert("item created")
addUser(fullname, email, password, age, occupation, Address);
}
});
var fetchUsers = () => {
try {
var userString = localStorage.getItem('userData');
return JSON.parse(userString);
} catch (error) {
return [];
}
};
var saveUser = (users) => {
localStorage.setItem('userData', JSON.stringify(users));
};
var addUser = (fullname, email, password, age, occupation, Address) => {
var users = fetchUsers();
var user = {
fullname,
email,
password,
age,
occupation,
Address
};
var duplicateUsers = users.filter(user => user.email === email);
if (duplicateUsers.length === 0) {
users.push(user);
saveUser(users);
return user;
}
};
/*************
signup popup
*************/
signUpBtn.addEventListener('click', () => {
signUpOver.style.display = 'block';
});
signUpOver.addEventListener('click', () => {
if(event.target == signUpOver){
signUpOver.style.display = "none";
}
});
/*************
signup popup
*************/
/*************
signin popup
*************/
signInBtn.addEventListener('click', () => {
signInOver.style.display = 'block';
});
signInOver.addEventListener('click', () => {
if(event.target == signInOver){
signInOver.style.display = "none";
}
});
/*************
signin popup
*************/
/** the end */
body {
width: 100%;
margin: 0;
background-color: #F8F9F9;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
align-content: center;
}
#mainPage,
#userPage {
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
align-content: center;
}
#userPage {
display: none;
}
/********************
overlay
********************/
.signup__overlay {
position: fixed;
display: none;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0,0,0,0.8);
z-index: 1;
}
.signup__content{
position: relative;
width: 100%;
max-width: 520px;
background-color: #ffffff;
opacity: 1;
margin: 64px auto;
padding: 20px;
}
.signin__overlay {
position: fixed;
display: none;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0,0,0,0.8);
z-index: 1;
}
.signin__content{
position: relative;
width: 100%;
max-width: 520px;
background-color: #ffffff;
opacity: 1;
margin: 64px auto;
padding: 20px;
}
/********************
overlay ending
********************/
.headerMain {
background-color: #000;
color: #fff;
width: 100%;
margin-bottom: 50px;
height: 50px;
display: flex;
flex-direction: row;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.headerUser {
background-color: #000;
color: #fff;
width: 100%;
margin-bottom: 50px;
height: 50px;
display: flex;
flex-direction: row;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.upButton {
margin-bottom: 20px;
}
.upButton, .inButton {
padding-top: 15px;
padding-bottom: 15px;
cursor: pointer;
width: 100%;
max-width: 200px;
background-color: #239B56;
border: #239B56;
color: snow;
}
label {
padding-top: 20px;
}
label,
input {
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>User system</title>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div id="mainPage">
<div class="signup__overlay">
<div class="signup__content">
<form>
<label for="name">Full Name</label>
<input required type="text" id="name" name="name">
<label for="email">Email</label>
<input required type="text" id="email" name="email">
<label for="password">Password</label>
<input required type="password" id="password" name="password">
<label for="age">Age</label>
<input required type="text" id="age" name="age">
<label for="occupation">Occupation</label>
<input required type="text" id="occupation" name="occupation">
<label for="address">Address</label>
<input required type="text" id="address" name="address">
<input type="submit" id="signupClicked">
</form>
</div>
</div>
<div class="signin__overlay">
<div class="signin__content">
<form>
<label for="email">Email</label>
<input required type="text" id="Email" name="email">
<label for="email">Password</label>
<input required type="Password" id="Password" name="Password">
<input type="submit" id="signinClicked">
</form>
</div>
</div>
<header class="headerMain">User System</header>
<section>
<button class="upButton" id="signUp">Sign Up</button>
<button class="inButton" id="signIn">Sign In</button>
</section>
</div>
<div id="userPage">
<header class="headerUser">User System</header>
<section>
</section>
</div>
<script src="js/index.js"></script>
</body>
</html>
Okay so here are several things we need to discuss about. Let's start with the code:
When you have a <input type="submit"> inside a form, the button will re-fresh the page when it's clicked. It's the behaviour by default of the submit button. That's why nothing is stored on the localStorage. To prevent this from happening, you need to use the event.preventDefault() method. Check out this link.
After fixing the preventDefault bug, we face another problem: the function fetchUsers returns null. That's because localStorage.getItem('userData') returns a null if nothing is on the localStorage. The try/catch dosn't work here, since localStorage.getItem('userData') dosn't throw an error. If nothing is there, it simply returns a null (but no error). Solucion: change your return to use a ternary operator:
return JSON.parse(userString) ? JSON.parse(userString) : [];
Using document.querySelector('#name') dosn't return what the user has written on that input. To get what the user writes on an input, you have to use: document.querySelector('#name').value
If you put the var fullname = document.querySelector('#name').value; on the global scope (at the begining of the script) it will take the value that the input had when the script was first loaded (which is... ""). You want to take that value every time the user clicks on the button. So you have to move those variables (fullname, email, password) inside the signupSubmitClicked.addEventListener.
And now the most important thing to discuss: why are you trying to store personal data on the localStorage? You need to be aware that the information on the localStorage is not secure, not really stored into any server, and not recommended at all. If you are doing this project to practice and learn it's okay. You can use this as a playground to learn. But remember: if you want to store personal information in a real-world way, you need to create a server (a back-end to your web).
Hi Opeyemi and welcome on StackOverflow.
First of all you have to know that this way of doing is good for testing, but it won't fit for any production applications.
The reason this is failing is because this function :
var fetchUsers = () => {
try {
var userString = localStorage.getItem('userData');
return JSON.parse(userString);
} catch (error) {
return [];
}
};
is actually returning a null value. Due to that null value, the rest of the code get stuck.
This part of the code will get stuck for example :
var duplicateUsers = users.filter(user => user.email === email);
Normally these errors appear in your console, so you really should check that out.
Once that is fixed it should be pretty easy to fix the rest

Notification show as input textbox click with jquery patterns

I don't know that I will explain my question well or not because I'm new on stack overflow. I've read the T&C and have tried my best to explain what I want to accomplish. I hope you understand what I'm asking.
I would like to create a system using javascript or jQuery that will display a popup box on the top or bottom of a browser window with custom text and colors defined in my css styles. The "notification" would tell users to about what they need to do in the text box like "Write your email" etc.
This is the code that will show you what I'd like them to look like:
<div class="warning"id="notification"><span>This is default message show first time</span></div>
<div class="information" id="notification"><span>Enter your registered Email ID</span></div>
<div class="error" id="notification"><span>Email ID is incorrect</span></div>
<div class="error" id="notification"><span>Email is correct - good : show me for 5 sec only after I will hide automatically if I am in green else show until cursor inside textbox.</span></div>
<input type="text" name="email" id="username"/>
<input type="text" name="mobile" id="phone"/>
<input type="submit" id="ok" name="done"/>
<style>#notification {
position:fixed;
width: 100%;
text-align: center;
z-index:99;
overflow:hidden;
}
#notification h2{
font-size:16px;
font-weight:400
}
/*#notification.showNote{
width:50%;
left:230px
}*/
/*error, info, notice, alert*/
.success,.warning,.error,.information{display: block; position: relative; padding:5px 20px}
.information{background-color:#3bafda}
.success{background-color:#8cc152}
.warning{background-color:#f6bb42}
.error{background-color:#e9573f}
.notify h2{color:#fff}</style>
Some tips:
ids are unique in each page. You can not define multiple elements with just one id. Instead, You should use class attribute`.
To do something after some seconds, You should use setTimeout function
You must know about jQuery selectors and some of its functions. Read available tutorials on the web.
To validate a value, You must know Regex
A simple working example of your question is this. Hope it helps
let time2Hide = 5000;
function f(selector) {
$(selector).show();
setTimeout(() => {
$(selector).hide();
}, time2Hide);
}
f("#warning");
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function onSubmit() {
let email = $("#email").text()
if(!email) {
f("#information" )
}
else if(validateEmail(email)) {
f("#success");
}
else {
f("#error")
}
}
/**********************************************/
/* notification styles */
.notification {
position: fixed;
width: 100%;
text-align: center;
z-index: 99;
overflow: hidden;
}
.notification h2 {
font-size: 16px;
font-weight: 400
}
/*#notification.showNote{
width:50%;
left:230px
}*/
/*error, info, notice, alert*/
#success,
#warning,
#error,
#information {
display: none;
position: relative;
padding: 5px 20px
}
#information {
background-color: #3bafda
}
#success {
background-color: #8cc152
}
#warning {
background-color: #f6bb42
}
#error {
background-color: #e9573f
}
.notify h2 {
color: #fff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning" class="notification">
<span>This is default message show first time</span>
</div>
<div id="information" class="notification">
<span>Enter your registered Email ID</span>
</div>
<div id="error" class="notification">
<span>Email ID is incorrect</span>
</div>
<div id="success" class="notification">
<span>Email is correct - good : show me for 5 sec only after I will hide automatically if I am in green else show until cursor inside textbox.</span>
</div>
<hr><br><br><br>
<input type="email" name="email" id="username" />
<input type="phone" name="mobile" id="phone" />
<input type="submit" id="ok" name="done" onclick="onSubmit()"/>
let time2Hide = 5000;
function hideAll() {
$("#error").hide();
$("#warning").hide();
$("#success").hide();
$("#information").hide();
}
function show(selector) {
hideAll();
$(selector).show();
}
function showNHide(selector) {
hideAll();
$(selector).show();
setTimeout(() => {
$(selector).hide(); show("#warning");
}, time2Hide);
}
$("#username")
.on("input click", () => {
show("#information");
})
.on("input", () => {
let email = $("#username").val();
if (!email) {
show("#information");
} else if (validateEmail(email)) {
showNHide("#success");
} else {
show("#error");
}
})
.on('focusout', () => {
show("#warning");
});
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function onSubmit() {
let email = $("#username").val();
if (!email) {
show("#information");
} else if (validateEmail(email)) {
showNHide("#success");
} else {
show("#error");
}
}
show("#warning");
/**********************************************/
/* notification styles */
.notification {
position: fixed;
width: 100%;
text-align: center;
z-index: 99;
overflow: hidden;
}
.notification h2 {
font-size: 16px;
font-weight: 400
}
/*#notification.showNote{
width:50%;
left:230px
}*/
/*error, info, notice, alert*/
#success,
#warning,
#error,
#information {
display: none;
position: relative;
padding: 5px 20px
}
#information {
background-color: #3bafda
}
#success {
background-color: #8cc152
}
#warning {
background-color: #f6bb42
}
#error {
background-color: #e9573f
}
.notify h2 {
color: #fff
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="warning" class="notification">
<span>This is default message show first time</span>
</div>
<div id="information" class="notification">
<span>Enter your registered Email ID</span>
</div>
<div id="error" class="notification">
<span>Email ID is incorrect</span>
</div>
<div id="success" class="notification">
<span>Email is correct - good : show me for 5 sec only after I will hide automatically if I am in green else show until cursor inside textbox.</span>
</div>
<hr><br><br><br>
<input type="email" name="email" id="username" />
<input type="phone" name="mobile" id="phone" />
<input type="submit" id="ok" name="done" onclick="onSubmit()" />

Force HTML form validation via JavaScript

I have created a HTML form which has two buttons (instead of a submit button), each programmatically sending the form to a unique form action address.
<form id="formExample">
<input type="text" id="input1" required>
<label type="button" onClick="form1()">Form Action 1</label>
<label type="button" onClick="form2()">Form Action 2</label>
</form>
The scripts:
form = document.getElementById("formExample");
function form1() {
form.action="example1.php";
form.submit();
}
function form2() {
form.action="example2.php";
form.submit();
}
Work well, responding to which button you press. However, the same html form validation that worked before (when using a 'submit' button), no longer shows a hint and the form sends regardless of whether there is input or not.
I have read that because I am calling the form.submit() programmatically, it bypasses the onSubmit() function of a form, which is where the validation takes place.
My question is: Can I programmatically force the onSubmit() so that I get the validation pop up? I must make clear that I am NOT wanting to create a JavaScript form validation, i.e. using an alert; rather, use JavaScript to enforce the HTML validation as found here, when you click submit: https://jsfiddle.net/qdzxfm9u/
You can merely change your button's type to submit and drop the form.submit() from your JS part.
So the HTML part becomes:
<form id="formExample">
<input type="text" id="input1" required>
<button type="submit" onClick="form1()">Form Action 1</button>
<button type="submit" onClick="form2()">Form Action 2</button>
</form>
This way, clicking any button does submit by itself, but before is executed the JS part:
form = document.getElementById("formExample");
function form1() {
form.action="example1.php";
}
function form2() {
form.action="example2.php";
}
EDIT
Warning: I originally based my solution on a copy of the OP HTML part, where the "pseudo-buttons" used a strange element <label type="input"...>, so I read (too quickly) as if it was <button type="button"...> and simply changed type from input to submit!
This way, it couldn't work as expected.
It is now corrected in the above code.
Maybe something like this :
var form = document.getElementById("formExample");
function form1() {
form.action="example1.php";
}
function form2() {
form.action="example2.php";
}
<form id="formExample">
<input type="text" id="input1" required>
<input type="submit" onClick="form1()" value="Form Action 1" />
<input type="submit" onClick="form2()" value="Form Action 2" />
</form>
How about making a dropdown list - could be radio buttons instead - containing the form two actions with one submit button like in this JS Fiddle, then having one function on form submit
var form = document.getElementById("formExample"),
select = document.getElementById("slct");
form.addEventListener('submit', function() {
if (select.value == 1) {
form.action = "example1.php";
} else {
form.action = "example2.php";
}
// alert for demo only
alert(form.action);
form.submit();
});
<form id="formExample">
<input type="text" id="input1" required>
<select id="slct" required>
<option></option>
<option value="1">Form Action 1</option>
<option value="2">Form Action 2</option>
</select>
<button type="submit">Submit</button>
</form>
function togglePassword(el){
var checked = el.checked;
if (checked) {
document.getElementById("password").type = 'text';
document.getElementById("toggleText").textContent= "Hide";
} else {
document.getElementById("password").type = 'password';
document.getElementById("toggleText").textContent= "Show";
}
}
function login()
{
var uname = document.getElementById("uname").value;
var password = document.getElementById("password").value;
if(uname === '')
{
alert("Please enter the user name.");
}
else if(password === '')
{
alert("Enter the password");
}
else
{
alert('Login Successful. Thank You!');
}
}
function clearFunc()
{
document.getElementById("uname").value="";
document.getElementById("password").value="";
<script type="text/javascript">
function togglePassword(el){
var checked = el.checked;
if (checked) {
document.getElementById("password").type = 'text';
document.getElementById("toggleText").textContent= "Hide";
} else {
document.getElementById("password").type = 'password';
document.getElementById("toggleText").textContent= "Show";
}
}
function login()
{
var uname = document.getElementById("uname").value;
var password = document.getElementById("password").value;
if(uname === '')
{
alert("Please enter the user name.");
}
else if(password === '')
{
alert("Enter the password");
}
else
{
alert('Login Successful. Thank You!');
}
}
function clearFunc()
{
document.getElementById("uname").value="";
document.getElementById("password").value="";
}
</script>
/* heading */
h1 {
display: block;
font-size: 2em;
font-weight: bold;
/* padding: 0% 1% 3% 6.5%; */
margin: 0% 35% -10% 36%;
}
h1:hover{
color:#4499d9 ;
transform: translateY(-5px);
}
/* bg image */
body {
background-image: url('img/bg4.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
/* Bordered form */
form {
/* border: 13px solid black; */
width: 27%;
height: auto;
position: absolute;
left: 10%;
margin-left: -3px;
top: 18%;
}
/* Full-width inputs */
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
/* Set a style for all buttons */
button {
background-color: #17234b;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 49%;
}
/* Add a hover effect for buttons */
button:hover {
background-color: #4499d9;
transform: translateY(-5px);
box-shadow: 1px 3px 7px #6f6d72;
}
#toggleText {
display: block;
}
/* Center the avatar image inside this container */
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
/* Avatar image */
img.avatar {
width: 30%;
border-radius: 20%;
box-shadow: 1px 3px 9px #6f6d72;
}
img.avatar:hover{
transform: translateY(-5px);
box-shadow: 7px 9px 9px #6f6d72;
}
/* Add padding to containers */
.container {
padding: 16px;
}
span.buttons{
width: 100%;
display: flow-root;
}
#toggleText{
float: left;
}
#toggle{
float: left;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>LOGIN PANEL</h1>
<!-- Login Form -->
<div class="form">
<form >
<div class="imgcontainer">
<img src="img/Login.jfif" alt="Login Avatar" class="avatar">
</div>
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="uname" name="uname"/>
<label for="password"><b>Password</b></label>
<input type='password'placeholder="Enter Your Password" name="password" id='password'/>
<input type='checkbox' id='toggle' onchange='togglePassword(this)'><span id='toggleText'>Show</span>
<span class="buttons">
<button type="submit" value="Reset" onclick="clearFunc()" class="btn">Reset</button>
<button type="submit" value="Login" class="btn" onClick="login()">Login</button>
</span>
</div>
</form>
</div>
</body>
</html>

Does anyone know why my multi-phase form won't work?

I am making a multi-phase form but it is not acting normal
I have written a lot of diffrent code for it but don't know why it is not working the way I want it
It has been two days working with it I am feeling stupid now
here is the code
HTML:
<div id="form-container">
<div id="phase-1">
<h3>Phase 01</h3>
<form>
<input id="fname" type="text" placeholder="First name">
<input id="lname" type="text" placeholder="Last name">
<input id="email" type="text" placeholder="Email">
<button id="phase-1-btn">Next</button>
</form>
</div>
<div id="phase-2">
<h3>Phase 02</h3>
<form>
<input id="pass" type="text" placeholder="Password">
<input id="cpass" type="text" placeholder="Confirm Password">
<button id="phase-2-btn">Next</button>
</form>
</div>
<div id="phase-3">
<h2>Thank You for Testing my pen</h2>
</div>
</div>
CSS :
#form-container{
height: 350px;
width: 300px;
margin-top: 80px;
margin-left: auto;
margin-right: auto;
background-color: #95a5a6;
font-family: "Slabo 27px";
position: relative;
box-shadow: 1px 1px 2px,
-1px -1px 2px;
}
#phase-1, #phase-2{
height: 100%;
width: 100%;
border-top: 3px solid #f39c12;
display: block;
}
#phase-1 h3, #phase-2 h3{
height: 10%;
width: 60%;
margin-left: auto;
margin-right: auto;
text-align: center;
font-size: 23px;
color: #fff;
}
#phase-1 form, #phase-2 form{
display: block;
height: 75%;
padding: 0;
padding-top: 15px;
margin: 0;
}
input{
display: block;
width: 80%;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
padding: 10px 20px;
border: none;
border-radius: 5px;
}
button {
display: block;
width: 60%;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
padding: 10px 5px;
background-color: #f39c12;
color: #fff;
font-weight: 600;
border: none;
border-radius: 6px;
}
#phase-2{
display: none;
}
#phase-3{
display: none;
height: 0;
width: 100%;
color: #000;
position: absolute;
top: 0;
left: 0;
background: #f39c12
}
#phase-3 h2{
width: 200px;
height: 60px;
margin-left: auto;
margin-right: auto;
margin-top: 135px;
text-align: center;
}
JS :
var fname, lname, email, pass, cpass;
function id( id ) {
return document.getElementById(id);
}
function phase1 () {
fname = id("fname").value;
lname = id("lname").value;
email = id("email").value;
if ( fname.length > 2 && lname.length > 2 && email.length > 2 ) {
id("phase-1").style.display = "none";
id("phase-2").style.display = "block";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase1 function
// add the event to the phase-1-btn
id("phase-1-btn").addEventListener("click", phase1());
/* phase 02 */
function phase2 () {
pass = id("pass").value;
cpass = id("cpass").value;
if ( pass.length > 2 && cpass.length > 2 ) {
id("phase-2").style.display = "none";
id("phase-3").style.display = "block";
id("phase-3").style.height = "100%";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase2 function
id("phase-2-btn").addEventListener("click", phase2());
Let's try this one. Then tell me what you see in the console.
<script>
function phase1()
{
window.console.log('phase1 function called');
var fname_val = document.getElementById('fname').value;
var lname_val = document.getElementById('lname').value;
var email_val = document.getElementById('email').value;
// verify values
window.console.log('fname_val='+fname_val + ' lname_val='+lname_val + ' email_val='+email_val);
if( fname_val.length > 2 && lname_val.length > 2 && email_val.length > 2 )
{
window.console.log('validation!! :)');
document.getElementById("phase-1").style.display = "none";
document.getElementById("phase-2").style.display = "block";
}
else
{
alert("Please fill the Form");
}
}
function phase2()
{
window.console.log('phase2 function called');
}
document.addEventListener("DOMContentLoaded", function(event) {
window.console.log("DOM fully loaded and parsed");
document.getElementById("phase-1-btn").addEventListener("click", phase1);
document.getElementById("phase-2-btn").addEventListener("click", phase2);
});
</script>
<div id="phase-1">
<h3>Phase 01</h3>
<input id="fname" type="text" placeholder="First name" />
<input id="lname" type="text" placeholder="Last name" />
<input id="email" type="text" placeholder="Email" />
<input type="button" id="phase-1-btn" value="Next" />
</div>
<div id="phase-2">
<h3>Phase 02</h3>
<input id="pass" type="text" placeholder="Password" />
<input id="cpass" type="text" placeholder="Confirm Password" />
<input type="button" id="phase-2-btn" value="Next" />
</div>
<div id="phase-3">
<h2>Thank You for Testing my pen</h2>
</div>
To submit a form you want to use a submit button (not classic button).
Have all of your inputs within the form tags.
Add the appropriate form tag attributes such as (action & method)
Use one form tag that wraps around everything with the submit button on the inside.
CSS will have no effect so no need to share that part.
Last but not least - Dont call yourself stupid. Stupid people never ask for help. Reaching out for help is how you improve your skillset.
If you insist on using Javascript to submit the form that is fine, but you want to make sure the form works with classic HTML first.
To make this a multi-step process you should try doing 1 form per page. You will need to understand session handling. You can display portions of the form at a time with Javascript which gives an impression of doing steps but still using 1 form.
<form action="" method="POST">
<script>
function toggleSection(x){
document.getElementById('sec'+x).style.display = "block";
}
</script>
<div id="sec1">
section 1 stuff
<input type="button" value="Continue" onclick="toggleSection(2);" />
</div>
<div id="sec2" style="display:none;">
section 2 stuff
<input type="button" value="Continue" onclick="toggleSection(3);" />
</div>
<div id="sec3" style="display:none;">
section 3 stuff
<input type="submit" value="Submit" />
</div>
</form>
here it is with the changes you ordered
var fname, lname, email, pass, cpass;
function el( id ) {
return document.getElementById(id);
}
function phase1 () {
fname = el("fname").value;
lname = el("lname").value;
email = el("email").value;
if ( fname.length > 2 && lname.length > 2 && email.length > 2 ) {
el("phase-1").style.display = "none";
el("phase-2").style.display = "block";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase1 function
// add the event to the phase-1-btn
el("phase-1-btn").addEventListener("click", phase1);
/* phase 02 */
function phase2 () {
pass = el("pass").value;
cpass = el("cpass").value;
if ( pass.length > 2 && cpass.length > 2 ) {
el("phase-2").style.display = "none";
el("phase-3").style.display = "block";
el("phase-3").style.height = "100%";
// end of if
} else {
alert("Please fill the Form");
}
} // end of phase2 function
el("phase-2-btn").addEventListener("click", phase2);

Categories

Resources