If click count number JavaScript - javascript

I'm building a demo login form. For the demo, I'd like two things to happen:
When the user clicks the login button for the first time, an error message appears.
When the user clicks the login button for the second time, they are directed to another page.
Here's how my code looks so far:
function toggleError() {
var toggleError = document.querySelector('.message--error');
toggleError.classList.toggle('error-toggled');
}
.message {
display: none;
}
.error-toggled {
display: block;
}
<div class="message message--error">
<span class="message__text">The login details you entered are incorrect.</span>
</div>
<form onsubmit="toggleError(); return false;" action="/" method="get" class="login__form" autocomplete="off">
<label for="email" class="srt">Email</label>
<input type="email" name="email" id="email" required placeholder="Email" class="input input--border-right">
<label for="password" class="srt">Password</label>
<input type="password" name="password" id="password" required placeholder="Password" class="input">
<div class="login__actions">
<button type="submit" class="button">Log In</button>
Lost your password?
</div>
</form>
Using onsubmit="toggleError(); return false;" achieves my first objective of displaying an error message.
How would I extend this function so the user is directed to a page when they click the button for a second time? I'm guessing I would write some type of loop?

Based on first two comments here a possible way:
<script>
var clickCounter=0;
function toggleError() {
//Increase the value by one
clickCounter++;
if (clickCounter == 1) {
//what ever you want to do
return false;
} else if (clickCounter == 2) {
//You need to change the value again
...
var toggleError = document.querySelector('.message--error');
toggleError.classList.toggle('error-toggled');
return false;
}
}
</script>

Related

How do I make a div element stay on a same position as before after page reload?

In the following code: https://jsfiddle.net/4gfqnyas/ there is a pure java script function that will move the div <div id="btn"></div> to either left or right (and also change the forms) when either Login or Register button is clicked.
How do I make the div stay in the exact same position as I left, after each reload (or after clicking on the register submit button). I don't want the div to reset back to Login position after reload(or after clicking on the register submit button).
For example: Let's say I click on Register, the div will move to the register and the form will also change to register. Now when I click on Register submit button, the div automatically goes to login and so does the form which makes it impossible for me to display any errors in the register form if the user entered invalid information. I want it to stay on the same form after a reload or after clicking the respective submit buttons.
To fix this, you can use localStorage.
Note that some super old browser don't support localStorage, but that is not a big thing, almost nobody has them.
Let me know if it works. :)
Here is a fixed version (CSS stays the same) :
HTML :
<div class="hero">
<div class="form-box">
<div class="button-box">
<div id="btn"></div>
<button type="button" id="loginButton" class="toggle-btn" onclick="login()">Login</button>
<button type="button" id="registerButton" class="toggle-btn" onclick="register()">Register</button>
</div>
<div class="social-icons">
<img src="images/fb.png">
<img src="images/gp.png">
<img src="images/tw.png">
</div>
<form method="POST" action="val_log.php" id="login" class="input-group">
<input name="Lname" type="text" class="input-field" placeholder="User ID" minlength="4" maxlength="15">
<input name="Lpassword" type="password" class="input-field" placeholder="Enter Password" minlength="5" maxlength="60">
<input name="Lrempass" type="checkbox" class="check-box"><span> Remember Password</span>
<button name="Lsubmit" type="submit" class="submit-btn"> Login </button>
</form>
<form method="POST" action="val_reg.php" id="register" class="input-group">
<input name="Rmail" type="email" class="input-field" placeholder="Email ID" >
<input name="Rname" type="text" class="input-field" placeholder="User ID" minlength="4" maxlength="15">
<input name="Rpassword" type="password" class="input-field" placeholder="Enter Password" minlength="5" maxlength="60">
<input name="REpassword" type="password" class="input-field" placeholder="Re-Enter Password" maxlength="60">
<input name="Rterms" value="selected" type="checkbox" class="check-box" ><span> I agree to the terms & conditions</span>
<button name="Rsubmit" type="submit" class="submit-btn" > Register </button>
</form>
</div>
</div>
JS :
var x = document.getElementById("login");
var y = document.getElementById("register");
var z = document.getElementById("btn");
console.log(x)
function register(){
x.style.left = "-400px";
y.style.left = "50px";
z.style.left = "110px";
}
function login(){
x.style.left = "50px";
y.style.left = "450px";
z.style.left = "0";
}
// Added code
if(localStorage){
if(localStorage.getItem('rememberButtonChoice')){
let getChoice = localStorage.getItem('rememberButtonChoice');
if(getChoice == "loginChoice"){
login();
}
else{
register();
}
}
}
let loginButton = document.getElementById('loginButton');
let registerButton = document.getElementById('registerButton');
loginButton.addEventListener('click', function(){
if(localStorage){
localStorage.setItem("rememberButtonChoice", 'loginChoice');
}
});
registerButton.addEventListener('click', function(){
if(localStorage){
localStorage.setItem("rememberButtonChoice", 'registerChoice');
}
});
When your page reload it loose all the data and set itself to default initialize data. You can make use of localStorage for keeping track of what you have clicked. Something similar to below example.
And you said you want to display error on page reload so in the first place why you want to reload . You can show them without reloading the page as well and if you are using server side form submission than you can use url query params to maintain the click history.
var x = document.getElementById("login");
var y = document.getElementById("register");
var z = document.getElementById("btn");
function register(){
x.style.left = "-400px";
y.style.left = "50px";
z.style.left = "110px";
window.localStorage.setItem("cur_page", "register");
}
function login(){
x.style.left = "50px";
y.style.left = "450px";
z.style.left = "0";
window.localStorage.setItem("cur_page", "login");
}
const cur_page = window.localStorage.getItem("cur_page");
switch (cur_page) {
case "login":
login();
break;
case "register":
register();
break;
default:
login();
}

Django, JS/JQuery validate inputs and disable submit button

I have a simple input params that are required. I want to disable my submit button until all the required fields are satisfied. Granted I am new to django, and the particular code I am working on is very old. As a result, post like this or this are not helping.
Current code that I am trying from one of the posts linked and including my own template
<script type="text/javascript">
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
$('#submit').on('click', function() {
var zip = $('#zip').val();
var email = $('#email').val();
var name = $('#name').val();
//if inputs are valid, take inputs and do something
});
<form class="form-horizontal" action="" method="get" id="dataform">
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-3">
<input class="col-md-12" id="zip" type="text" placeholder="Enter zip code" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="name" type="text" placeholder="Enter last name" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="email" type="email" placeholder="Enter email address" aria-required="true">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn btn-primary" id="submit" type="submit">Submit</div>
</div>
</div>
</form>
any help on disabling my submit button until input fields are not validated/filled is much appreciated. Again, new to django and I am unable to use existing threads on said topic
From your current code, looks like your selector for the submit input is not actually getting the submit "button". Currently, your template defines the submit as a div and not an input, thus your selectors should be $("div[type=submit]") not $("input[type=submit]")
Better yet, just select by div id $('#submit')
Instead of targeting attributes, I was targeting props. Below is the fix for my particular issue.
if (inputsWithValues === 3) {
$("div[type=submit]").attr("disabled", false);
} else {
$("div[type=submit]").attr("disabled", 'disabled');
}

Each time I click button page refreshes

Title virtually says it all. Each time I click calculate button the page just refreshes. I added the stopPropagation and preventDefault which worked on my other button on a different page, however in this situation they don't seem to work. Any thoughts?
JS:
/******** Loan Balance Constructor *********/
function LoanBalance(mLoanAmt, mIntRate, nMonths, mMonthlyPmt){
//Declarations
this.loanAmount = mLoanAmt;
this.interestRate = mIntRate;
this.numbOfMonths = nMonths;
this.monthlyPayment = mMonthlyPmt;
//Calculates Remaining Balance
this.calculateRemaining = function(){
console.log(this.loanAmount);
console.log(this.interestRate);
console.log(this.numbOfMonths);
console.log(this.monthlyPayment);
//COME BACK TO FIX THE FORMULA
var remainingBalance = this.loanAmount*(Math.pow(1+this.interestRate, this.numbOfMonths) -
(this.monthlyPayment*(Math.pow(1 + this.interestRate, this.numbOfMonths) - 1) / this.interestRate));
return remainingBalance;
}
return this.calculateRemaining()
}
function newBalanceObject(e){
e.stopPropagation();
e.preventDefault();
var balanceObject = new LoanBalance(document.getElementById("loanAmount").value, document.getElementById("interestRate").value,
document.getElementById("numMonthsPaid").value, document.getElementById("sliderDuration").value);
var result = balanceObject.calculateRemaining();
document.getElementById("remainingBalanceTag").innerHTML = "Your remaining balance is: " + "$" + result.toFixed(2);
}
HTML:
<div id="remainingBalance">
<h1 class="text-center">Loan Balance Calculator</h1>
<form>
<div class="form-group">
<label for="loanAmount">Loan Amount:</label>
<input class="form-control" id="loanAmount">
</div>
<div class="form-group">
<label for="interestRate">Interest Rate:</label>
<input class="form-control" id="interestRate" placeholder="Please enter number as a decimal">
</div>
<div class="form-group">
<label for="numMonthsPaid">Number of Months Paid: </label>
<input id="numMonthsPaid" type="text" data-slider-min="0" data-slider-max="600" data-slider-step="1" data-slider-value="300">
<div class="form-group">
<label for="sliderDuration">Loan Duration: </label>
<input id="sliderDuration" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="600" data-slider-step="1" data-slider-value="300"/>
</div>
<button id="calcButton" class="btn btn-default">Calculate</button>
</form>
<h1 class="text-center" id="remainingBalanceTag"></h1>
</div>
The form is getting submitted by default. You need to intercept the submission event and stop the default's browser action.
Since you haven't specified the action on the form element, it's simply refreshing the page, because it doesn't know where to send the data to.
Here's a sample code which shows how to intercept and stop all forms fom being submitted by the browser. Adjust it according to your setup so you only prevent submission of the forms that you want prevented.
Array.from(document.forms).forEach(form => {
form.addEventListener('submit', e => e.preventDefault())
}

How to change button state in javascript

I need to code a function in Javacript that updates the button colour and enables it when all fields are valid.
See picture below to understand the user interaction with the form
When the admin wants to update an user the update button needs to be green only if the following apply
At least one edit button is enabled. (When the edit button is enabled the respective fields is deleted and the user can write something)
The field must be validated in real time
If I uncheck the field the script has to revalidate the other open fields. For Instance if the open field is blank the button should be red but if I close the field and another field was enabled and filled with valid text (lets assume just 1 character means valid) the button from red should turn green
Could you please help me to figure this out. I think a solution is to use the JQuery keyup function but it is restricted only to one field. I need instead something more global.
Is there a way in javascript to create a global button listener than be useful for this scenario
In addition when I turn on the password checkbox two fields are enabled and the button should be valid only if password is valid and it matches with confirmed password
Please see below a brief summary of the jsp page
I have omitted the small icons of the password fields and the bootstrap part of the code
<sf:form class="form-horizontal"
role="form"
id="formsubmit"
method="POST"
action="${pageContext.request.contextPath}/updateprofile"
commandName="user">
<sf:input type="text" class="form-control" value="${user.username}" path="username" readonly="true"></sf:input>
<input type="checkbox" class="form-control" name="email-checkbox" checked />
<sf:input id="emailInput" type="text" class="form-control" path="email" placeholder="Type Email" name="email" disabled="true" />
<input type="checkbox" class="form-control" name="first-name-checkbox" checked />
<sf:input id="nameInput" type="text" class="form-control" placeholder="Type First Name" path="firstName" name="firstName" disabled="true" />
<input type="checkbox" class="form-control" name="last-name-checkbox" checked />
<sf:input id="surnameInput" type="text" class="form-control" placeholder="Type Last Name" path="lastName" name="lastName" disabled="true" />
<input type="checkbox" class="form-control" name="password-checkbox" checked />
<input id="password" type="password" class="form-control" name="password" placeholder="Insert Password" disabled>
<input id="confirmpassword" type="password" class="form-control" name="confirmpassword" placeholder="Confirm Password" disabled>
<button id="updateUserBtn" type="submit" class="btn btn-danger" data-loading-text="Creating User..." disabled>Update User</button>
</sf:form>
My first attemp with javascript is below and it works only for the password fields but it is not connected with the edit button
$("input[type=password]").keyup(
function() {
var ucase = new RegExp("[A-Z]+");
var lcase = new RegExp("[a-z]+");
var num = new RegExp("[0-9]+");
if ($("#password").val().length >= 8) {
$("#8char").removeClass("glyphicon-remove");
$("#8char").addClass("glyphicon-ok");
$("#8char").css("color", "#00A41E");
} else {
$("#8char").removeClass("glyphicon-ok");
$("#8char").addClass("glyphicon-remove");
$("#8char").css("color", "#FF0004");
}
if (ucase.test($("#password").val())) {
$("#ucase").removeClass("glyphicon-remove");
$("#ucase").addClass("glyphicon-ok");
$("#ucase").css("color", "#00A41E");
} else {
$("#ucase").removeClass("glyphicon-ok");
$("#ucase").addClass("glyphicon-remove");
$("#ucase").css("color", "#FF0004");
}
if (lcase.test($("#password").val())) {
$("#lcase").removeClass("glyphicon-remove");
$("#lcase").addClass("glyphicon-ok");
$("#lcase").css("color", "#00A41E");
} else {
$("#lcase").removeClass("glyphicon-ok");
$("#lcase").addClass("glyphicon-remove");
$("#lcase").css("color", "#FF0004");
}
if (num.test($("#password").val())) {
$("#num").removeClass("glyphicon-remove");
$("#num").addClass("glyphicon-ok");
$("#num").css("color", "#00A41E");
} else {
$("#num").removeClass("glyphicon-ok");
$("#num").addClass("glyphicon-remove");
$("#num").css("color", "#FF0004");
}
if ($("#password").val() == $("#confirmpassword").val()
&& ($("#confirmpassword").val() != 0)) {
$("#pwmatch").removeClass("glyphicon-remove");
$("#pwmatch").addClass("glyphicon-ok");
$("#pwmatch").css("color", "#00A41E");
} else {
$("#pwmatch").removeClass("glyphicon-ok");
$("#pwmatch").addClass("glyphicon-remove");
$("#pwmatch").css("color", "#FF0004");
}
if ($("#password").val().length >= 8
&& ucase.test($("#password").val())
&& lcase.test($("#password").val())
&& num.test($("#password").val())
&& $("#password").val() == $("#confirmpassword").val()
&& ($("#confirmpassword").val() != 0)) {
$("#updateUserBtn").removeClass("btn-danger");
$("#updateUserBtn").addClass("btn-success");
$("#updateUserBtn").prop('disabled', false);
} else {
$("#updateUserBtn").removeClass("btn-success");
$("#updateUserBtn").addClass("btn-danger");
$("#updateUserBtn").prop('disabled', true);
}
});
A keyup handler attached to the form element will be called for any field within it having a keyup event. That is because most events bubble up through all their ancestors and can be listened for at any level.
Small example as requested :)
$("form").keyup(
function() {
// your existing code here
});
If you want to target only specific inputs for the changes, you could use a delegated handler instead attached to the form (this one is using the specific form id):
$("#formsubmit").on('keyup', 'input[type=text],input[type=password]',
function() {
// your existing code here
});
This applies the selector at event time so is quite efficient, and also means the this value will be the control that changed (if that is useful to you).
As a general jQuery guideline, only run selectors once and save the element. This is faster & shorter and usually more readable. Also you can chain most jQuery functions together.
e.g.
var $password = $("#password");
var $8char = $("#8char");
if ($password.val().length >= 8) {
$8char.removeClass("glyphicon-remove").addClass("glyphicon-ok").css("color", "#00A41E");

Why is "enter" not working for my form?

Here is the code, I can't figure out why enter/return isn't working! Is it because it's inline?
HTML
<div class="wrap"><form name="login" style="margin: 0px">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<input TYPE="text" NAME="pass" size="17" onKeyDown="e.keyCode == 13;" id="fname" class="cool"><br><input type="button" value="LOGIN" class="asbestos-flat-button" onClick="TheLogin(this.form)">
</form>
</div>
JS
<script language="JavaScript" type="text/javascript">
<!--- PASSWORD PROTECTION SCRIPT
function TheLogin() {
var password = 'password';
if (this.document.login.pass.value == password) {
top.location.href="home.html";
}
else {
location.href="index.html";
}
}
// End hiding --->
</script>
I'm learning JS so any help would be so awesome!
UPDATE
Thanks for your help. Still not working when integrated. The page doesn't load the home.html when I hit enter/return. Instead I get no refresh, and the address bar has the url http://example.com/?pass=password.
If I click the button it does load the home.html!
thanks!
Here I wrote a JSFiddle with the working example.
In the HTML code:
Remove onKeyDown="e.keyCode == 13;" from the <input> text element.
Remove onClick="TheLogin(this.form)" from the <input> button element.
Change the type of input button from 'button' to 'submit'. In this way, when you press "enter" in the input text form the form is submitted.
Intercept the "submit" event in the form, adding onSubmit="theLogin(this.form)" on <form> element.
Note: I have renamed the function name from "TheLogin" to "theLogin" because in JavaScript the functions begins with lowercase letters if they are not constructors.
The HTML code:
<div class="wrap">
<form name="login" style="margin: 0px" onSubmit="theLogin(this.form)">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<INPUT TYPE="text" NAME="pass" size="17" id="fname" class="cool">
<br>
<input type="submit" value="LOGIN" class="asbestos-flat-button">
</form>
</div>
And the JavaScript code:
theLogin = function() {
var password = 'password';
if (this.document.login.pass.value === password) {
top.location.href = "home.html";
} else {
location.href = "index.html";
}
}
You have missed the <input type="submit">, without it you can't use the Enter key to submit the form.

Categories

Resources