Javascript toggle between show and hide a password - javascript

I have been working on a project that requires me to toggle between showing and hiding the password in a password field.
The JS code I came up with is:
<script>
function text(item) {
if (document.getElementById('password').type = "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
</script>
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input type="password" id="password" />
For some reason, it works just fine when toggling between password -> text, but fails to do the opposite.
What am I doing wrong?

You are missing an = in the if condition
if(document.getElementById('password').type="password"){
^^^^
Should be
if(document.getElementById('password').type=="password"){
Otherwise it will assign the type password to the field and it will return true always
function text(item) {
if (document.getElementById('password').type == "password") {
document.getElementById('password').type = "text";
} else {
document.getElementById('password').type = "password";
}
}
<input type="checkbox" id="logon-show-password" name="showpassword" class="tickable" onclick="text(this)">
<input id="password" type="password" />

Related

I can not trigger the alert when the form is empty after developing a clean code in pure JavaScript

The small code in pure HTML, without forgetting to set the method for get:
<form action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome"><br>
<input id="email" type="text" name="email" placeholder="E-mail"><br>
<textarea id="message" name="name" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio"></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
I refactored and made a clean code of the dirty multiple if-else statements, simplifying. After it, I can not trigger the alert.
The code let send = document.getElementById("send"); checks the code <input type="submit" value="Enviar" id="send"><br>.
Before, in a dirty code, I had many document.getElementById("email").value == "" and simplified to:
const fields = new Set([
'name',
'email',
'message',
]);
I simplified three 'if-else statements along with these if-else statements of identifiers. Firstly, it will check if the fields are empty, go to verify the length, 1 indicates only an empty field and > 1 indicates more empty fields. Else they will check the fields are full and submit.
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Thank you! The message was sent successfully")
}
}
Finally, the code send.addEventListener("click", alert) indicates to click the function when sending, and addEventListener will trigger the alert.
Complete code in JavaScript:
let send = document.getElementById("send");
const fields = new Set([
'name',
'email',
'message',
]);
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Agradecemos, mensagem enviada com sucesso!")
}
}
send.addEventListener("click", alert)
I will suggest that you create an event listener for invalid on the form. This will be called when one of the required fields empty/invalid (see the required attribute on all the fields). I made a custom alert that shows.
var alert = document.getElementById('alert');
alert.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON')
alert.classList.remove('show');
});
document.forms.form01.addEventListener('submit', e => {
console.log('The form will submit');
});
document.forms.form01.addEventListener('invalid', e => {
e.preventDefault();
alert.classList.add('show');
}, true);
#alert {
display: none;
}
#alert.show {
display: block;
}
<form name="form01" action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome" required><br>
<input id="email" type="text" name="email" placeholder="E-mail" required><br>
<textarea id="message" name="message" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio" required></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
<div id="alert">The fields are required! <button>OK</button></div>
This is overruling the default behavior in the browser. In any case I think the required attribute is the right way to go.
You may like to do something like this with your function:
function showAlerts(){
var allInputs = document.querySelectorAll('#name, #email, #message');
if(null != allInputs){
for(var i in allInputs){
if(!isNaN(i)){
// here you can check for values, emptiness etc
if(allInputs[i].value.trim() === ''){
// this field is empty
alert('This field is required!');
}
...
}
}
}
}

I'm trying to validate multiple HTML Form inputs with javascript, and change css for invalid ones, what is the best way to do this?

I'm trying to validate an HTML form, trying to check if answers are filled in, and an e-mail is an actual e-mail adress. I want to proceed when all fields are valid. When some fields are not valid, change the css in to another class (so it becomes red to show that it is wrong.)
I have tried to validate each input seperately, but i believe there should be an easier way. Can somebody show me?
Current HTML:
<div class="form-group" id="stage1">
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
</div
I can't use HTML default validation, since I have created a multi-step form.
Thanks in advance,
Brandon
You can iterate through inputs this will assist validating your messy items:
window.onload = () => {
const allInputs = document.querySelectorAll(".form-control"); // or you may assign custom class or select by input tag..
let isAllvaild = true;
allInputs.forEach((element) => {
if (!validateAll(element.value, element.type)) { isAllvaild = false; break; }
});
if (isAllvaild) {
afterValidation(); // to keep things clean
}
}
function validateAll(value, type) {
if (type === "text") {
} else if (type === "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,}))$/;
let ck = re.test(String(value).toLowerCase());
if (ck) {
// set errors here..
} else {
// maybe remove errors if added previously..
}
return ck;
} else if (type === "phone") {
} else if (type === "other") {
} // add whatever needed..
}
function afterValidation() {
// at this point each input contains valid data.. proceed to next step..
// document.querySelector("#my_id").classList.add("display-block");
// ..
}
you can validate based on their type, so i think u would have two functions, one for email and another one for text fields. for instance:
if(textValidation() && emailValidation()){
submit()
}
emailValidation(){
return email ? true : false
}
textValidation(){
return text ? true : false
}
What about that? It will let you loop through every input and you can also do some specific validations. I know, it is not the smartest function ever, but it can be useful. (ofc you should make some better checking for email pattern (regular expressions are good for that /^.+?#.+..+$/m) and registration number (regex could be cool for that too: /^[\d]*$/m)
function validateInputs ()
{
const inputs = document.querySelectorAll('div[class=row] input');
for (let index = 0; index < inputs.length; index++)
{
const input = inputs[index];
let valid = false;
if (input.value && input.value.trim() !== '')
{
//here you can add specific validations for each id, maybe you can also use switch here
if (input.getAttribute('id') === 'email')
{
//of course, email also need to validate, if dot is present, regular expression might be the best option
if (input.value.indexOf('#') !== -1)
{
valid = true;
}
}
else
{
valid = true;
}
}
if (!valid)
{
input.classList.add('error');
}
else
{
input.classList.remove('error');
}
}
};
window.addEventListener('load', function () {
document.querySelector('button').addEventListener('click', validateInputs)
});
input.error {
background-color: red;
}
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
<button>validate</button>
For fields like text you need to write your own validation, since it is totally up to you. But in case of fields like email or url you can use build in functions like the HTMLFormElement.checkValidity() method to see if the form contains a field that does not have a valid input, for example a input with type email and a value of foobar would return false from the validity check.
Then you can look inside the form and search for all inputs that are invalid with the :invalid selector in querySelectorAll(). It will return a NodeList with the invalid form elements inside of it.
const form = document.querySelector('form');
form.addEventListener('input', event => {
if (form.checkValidity() === false) {
const invalids = form.querySelectorAll(':invalid');
for (const input of invalids) {
console.log(`${input.id} is invalid`);
}
}
});
<form>
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="url" id="website" class="form-control" placeholder="Website*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</form>
You can use this code between a script tag :
const form = document.querySelector('form'); form.addEventListener('input', event => { if (form.checkValidity() === false) { const invalids = form.querySelectorAll(':invalid'); for (const input of invalids) { console.log(`${input.id} is invalid`); } } });
Or use a Bootstrap classes to validate your form

Use JavaScript to change the href Tag depending on input field

I want to make the link in this change depending on whether the password is correct. I want to set one password and I only know html and minimal JS. I think I have it set so that when the password is wima it will change the href and allow the link to work. That doesn’t happen. Can I have some help?
function login()
var password = getElementById("password"); {
if (password = "wima") {
getElementById("submit").href = "/pages/home.html";
} else {
getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA"><br> Password
<input id="password" type=password placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
There are a few issues with your JavaScript.
<script language="JavaScript">
function login()
var password = getElementById("password"); // this gets the element, not the value of the element
{ // this curly brace is in the wrong place
if (password = "wima") { // this sets the value of the password var to "wima"
getElementById("submit").href="/pages/home.html";
}
else {
getElementById("submit").href="index.html";
}
}
</script>
Here is your code, cleaned up.
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") { // use == to compare value
document.getElementById("submit").href="/pages/home.html";
}
else {
document.getElementById("submit").href="index.html";
}
}
</script>
Another issue here is that you shouldn't be changing the href on the element used to execute the login() function.
You could redirect the user to the new page like so:
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") {
window.location.href="/pages/home.html";
}
else {
window.location.href="index.html";
}
}
</script>
I guess you are doing it wrong if you want to change the href value based upon input type text. You should make a blur/change event on password input text. Based upon password value when user clicks on href he should be redirected accordingly.
Check this out:
function login() {
var _password = document.getElementById("password").value;
if ("wima" == _password) {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA">
<br> Password
<input id="password" type=password placeholder="WIMA" onblur="login()">
<br>
<a class="button" id="submit" href="#">
Submit
</a>
</p>
Here is a form validator with a switch.
function validateForm() {
var x = document.forms["myForm"]["password"].value;
switch (x) {
case "":
alert("Name must be filled out");
return false;
break;
case "wima":
return true;
break;
default:
alert("Error: Wrong Password.");
document.location.href = "https://stackoverflow.com/search?q=notloggedin";
// Replace the link above with your error link return
return false;
}
}
<!-- Replace action link with your successful link -->
<form name="myForm" action="https://stackoverflow.com/search?q=login" onsubmit="return validateForm()" method="post">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
Your password is visible in text if someone inspects the html/javascript. So this method of security is not advised. For basic concepts it is interesting to have a link change based on input. Try this.
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" >
Submit
</a>
</p>
<script>
var password = document.getElementById('password');
password.addEventListener('change', enableLogin);
var submit = document.getElementById('submit');
function enableLogin() {
if (password.value == "wima") { // it is an easy mistake (= or ==)
submit.href = "/pages/home.html";
} else {
submit.removeAttribute('href');
}
}
</script>
A few things happened here:
The value inside a <input> is accessed by .value;
You misplaced the {
getElementById is not a global method it has to be called on the element you want to select in (in your case the document itself)
To test if two values are equal use === in js
function login() {
var password = document.getElementById("password").value;
if (password === "wima") {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>

javascript keyup to change divs not just text

I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>

Prevent submission if fields do not match

I am using JS to check if two fields match but I need a way to disable the submit button if they fail to match and then enable once they do match:
<label>New password:</label><br><input type="password" name="new_password" id="password1"/><br><br>
<label>Confirm password:</label><br><input type="password" name="new_password_check" id="password2" /><br><br>
<p id="validate-status"></p>
$(document).ready(function() {
$("#password2").keyup(validate);
});
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
}
else {
$("#validate-status").text("Passwords Do Not Match!");
}
}
UPDATED
<form method="post" action="password_change.inc.php">
<input type="hidden" name="user_id" value="<? echo $_SESSION['user_id']; ?>" />
<label>New password:</label><br><input type="password" name="new_password" id="password1"/><br><br>
<label>Confirm password:</label><br><input type="password" name="new_password_check" id="password2" /><br><br>
<p id="validate-status"></p>
<input id="#submit-button" type="submit" value="Change password" />
</form>
<script>
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
$('#submit-button').prop('disabled', false);
}
else {
$("#validate-status").text("Passwords Do Not Match!");
$('#submit-button').prop('disabled', true);
}
}
</script>
I have updated my code as per a kind suggestion below but it will still allow me to post the form without disabling until the fields match...
If your submit button id is "submit", you can do :
$("#submit").prop('disabled', true);​
(you might want to validate on clicking the submit button also)
So you should try something like :
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
$("#submit").prop('disabled', false);​
}
else {
$("#validate-status").text("Passwords Do Not Match!");
$("#submit").prop('disabled', false);​
}
But I would suggest you to write it this way:
As you are submitting the form, it's better to do the validation on submitting the form, because by calling validate on keyup you will be doing lot of unnecessary work.
<input id="submit" type="submit" value="Change password" onSubmit="return validate();" />
function validate(){
return ($("#password1").val() === $("#password2").val());
}
writing onSubmit=" return validate(); in your form submit button prevents the form from submitting when the validate function returns false. So you don't need to write any other code. This should be enough.
Give both password elements a class and do a .blur().
$('.myClass').blur(function () { value is the same enable submit, else disable });
I would put a check on the submit function as well and if the values are not the same return false and some message saying the passwords don't match
Firstly you need to remove that # from your input id. It would probably make sense to disable it on load as well.
input id="submit-button" type="submit" value="Change password" disabled="true"
Then just set a keyup listener on both password fields
$("#password1, #password2").keyup(function (e) { validate(); });
(Based on your updated code)
Apologies for adding to a 5-year old question, but here is another way of doing it...
<form method="post" action="password_change.inc.php">
<input type="hidden" name="user_id" value="<? echo $_SESSION['user_id']; ?>" />
<label>New password:</label><br><input type="password" name="new_password" id="password1"/><br><br>
<label>Confirm password:</label><br><input type="password" name="new_password_check" id="password2" /><br><br>
<p id="validate-status"></p>
<input id="submit-button" type="submit" value="Change password" />
</form>
<script>
$('#password1, #password2').keyup(validate); // Allows for interchangeable user text - Example, if user types in password1 field, but actually has password2 field with the correct password, user can correct password1 field and things match/validate
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$('#validate-status').css({'background' : 'green'});
$('#validate-status').text('Passwords Match');
// Below commented out code works too...
//$('#submit-button').prop('disabled', false);
$('#submit-button').css({'display' : 'block'}); // Bring the submit button back...
}
else {
$('#validate-status').css({'background' : 'red'});
$('#validate-status').text('Passwords do NOT match - Please fix');
// Below commented out code works too...
//$('#submit-button').prop('disabled', true);
$('#submit-button').css({'display' : 'none'}); // Do not display the submit button - user has no choice but to correct passwords and make them match...
}
}
</script>
Fiddle: https://jsfiddle.net/8kLypb7q/1/
You're almost there. Set the disabled property on your submit button (which appears to be missing from your pasted code). Assuming your submit button has an id submit-button:
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("Passwords Match!");
$('#submit-button').prop('disabled', false);
}
else {
$("#validate-status").text("Passwords Do Not Match!");
$('#submit-button').prop('disabled', true);
}
}
An optimised version would "cache" the elements like so:
var $password1 = $("#password1"),
$password2 = $("#password2"),
$statusMessage = $("#validate-status"),
$submitButton = $('#submit-button');
function validate() {
if($password1.val() == $password2.val()) {
$statusMessage.text("Passwords Match!");
$submitButton.prop('disabled', false);
}
else {
$statusMessage.text("Passwords Do Not Match!");
$submitButton.prop('disabled', true);
}
}

Categories

Resources