Html input show password

The Options for Password Revealing Inputs

If you use that, you get the obfuscated bullet-points when you type into it, like: •••••••• That’s the web trying to help with security. If it didn’t do that, the classic problem is that someone could be peering over your shoulder, spying on what you’re entering. Easier than looking at what keys your fingers press, I suppose. But UX has evolved a bit, and it’s much more common to have an option like: ☑️ Reveal Password? I think the idea is that we should have a choice. Most of us can have a quick look about and see if there are prying eyes, and if not, we might choose to reveal our password so we can make sure we type [email protected] correctly and aren’t made to suffer the agony of typing it wrong 8 times. So! What to do?

Option 1: Use type=»password» , then swap it out for type=»text» with JavaScript

This is what everybody is doing right now, because it’s the one that actually works across all browsers right now.

const input = document.querySelector(".password-input"); // When an input is checked, or whatever. if (input.getAttribute("type") === "password") < input.setAttribute("type", "text"); >else

The problem here — aside from it just being kinda weird that you have to change input types just for this — is password manager tools. I wish I had exact details on this, but it doesn’t surprise me that messing with input types might confuse any tool specifically designed to look for and prefill passwords, maybe even the tools built right into browsers themselves.

Option 2: Use -webkit-text-security in CSS

This isn’t a real option because you can’t just have an important feature work in some browsers and not in others. But clearly there was a desire to move this functionality to CSS at some point, as it does work in some browsers.

input[type="password"] < -webkit-text-security: square; >form.show-passwords input[type="password"]

Option 3: input-security in CSS

Читайте также:  Http chipeasy upan cc byreport php

form.show-passwords input[type="password"]

I like it. Simple. But I don’t think any browser supports it yet. So, kinda realistically, we’re stuck with Option #1 for now.

Источник

Hide/Show Password using Eye icon in HTML and JavaScript

In this tutorial, I will learn how to hide and show password using eye icon in HTML and JavaScript. I implemented it for one of my projects as below.

This very useful feature you should have on your login form.

There are simple two steps to follow. First, create the HTML login form. Secondly, show/hide password when the user clicks on the eye icon.

Watch live demo

Don’t miss any of such tips…

Let’s see it step-by-step. I will walk you through the complete code.

1. Create HTML Login form with Eye Icon

We are going to place the eye icon inside the password text field. We can use the eye icon from the awesome font script library.

First of all import the awesome font Stylesheet into your HTML form page.

Use the tag to display the eye icon. This icon is also known as the visibility eye icon.

Use the below CSS to put the eye icon at the end of the password text field.

margin-left: -30px; cursor: pointer;

If you are new to CSS, refer to how to add CSS in HTML.

Put this tag below the passwords input field. This is how the sample form will look like with the password field.

2. Add JavaScript to Toggle Show/Hide Password

Copy and paste the below code into your JavaScript. This code is self-explanatory if you are familiar with the JavaScript basics.

const togglePassword = document.querySelector('#togglePassword'); const password = document.querySelector('#id_password'); togglePassword.addEventListener('click', function (e) < // toggle the type attribute const type = password.getAttribute('type') === 'password' ? 'text' : 'password'; password.setAttribute('type', type); // toggle the eye slash icon this.classList.toggle('fa-eye-slash'); >);

You can also insert this code in your HTML page with tag.

Читайте также:  Java classpath from directory

Show/Hide Password in Django

In the sample picture shown above, I have implemented it for one of my websites developed using the Django Python framework. If you are developing it for Django, refer registration and login form in Django.

That’s all. Now you can hide and show password using eye icon in HTML with simple JavaScript and CSS code.

If you find any difficulties or need any customization, let me know in the comment section below.

Источник

Как задать отображение паролей в поле формы

От автора: на большинстве веб-сайтов при заполнении пароля в форме либо для регистрации, либо для входа в систему вы часто увидите кнопку (или флажок), с помощью которой можно задать отображение паролей. Это часто бывает полезно для пользователей, и пользователь, если не уверен, может проверить, не сделали ли они ошибку.

В этом уроке мы создадим аналогичный проект, в котором мы можем ввести наш пароль в форме и установить флажок, чтобы отображать или скрывать его. Давайте начнем. Требования:

Прежде чем мы начнем, сначала нужно иметь несколько вещей. Некоторые из требований заключаются в следующем: HTML, CSS, Основные знания JavaScript (ES6), DOM.

Основное понимание вышеперечисленных навыков достаточно для того, чтобы вы могли следовать и понимать код в уроке. Для контекста это образец того, что мы будем строить. В конце этого урока мы будем иметь что-то вроде этого:

Онлайн курс по JavaScript

Научитесь создавать приложения со сложными интерфейсами

Это основной язык для современной веб-разработки — почти 100% сайтов работает на JavaScript. Освойте его с нуля всего за 4 месяца, и вы сможете зарабатывать от 70 000 рублей.

Окончательный фрагмент кода будет предоставлен в ссылке Codepen в конце статьи.

Настройка нашей среды

Откройте редактор кода. Я использую Visual Studio Code. Вы можете использовать то, с чем вам больше всего нравится.

Внутри редактора создайте каталог с именем password-toggle (используйте любое имя, которое хотите, это просто для описательных целей)

Внутри каталога password-toggle:

Ваша файловая структура должна быть такой:

Источник

Показать и скрыть пароль в html-формe с помощью JavaScript и CSS.

Статьи по JavaScript

В этом руководстве вы узнаете, как скрывать и отображать пароли в поле ввода формы.

Читайте также:  Html email templates width

Для этого нам потребуется использовать следующие языки и фреймворки:

  • HTML5, чтобы создать форму.
  • CSS, чтобы указать местоположение иконки, которая будет показывать и скрывать пароль.
  • Bootstrap 4, фреймворк, который поможет нам сверстать форму.
  • FontAwesome 5, фреймворк, отображающий иконку, с помощью которых можно взаимодействовать с элементами формы.
  • JavaScript, который содержит слушающие события, позволяющие взаимодействовать с элементами формы.

Подключение bootstrap, fontawesom и код HTML

Для начала нам нужно подключить фреймворки, которые мы будем использовать. Напоминаем, что нам понадобятся и Bootstrap 4, и Fontawesome 5. Поместим их в верхнюю часть нашей веб-страницы.

link type="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/> link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" integrity="sha256-h20CPZ0QyXlBuAw7A+KluUYx/3pK+c7lYEpqLTlxjYQ hljs-attr">crossorigin="anonymous" />
Code language: HTML, XML (xml)

Следующим шагом будет добавление элементов формы, которые мы хотим показать пользователю.

div class="container"> form name="contact" id="contact" action="" method="post"> div class="form-group"> label for="department"> Введите пароль: input type="password" name="password" class="form-control password1" value="pass" placeholder="" /> span class="fa fa-fw fa-eye password-icon show-password"> span> label> div> div class="form-group"> label for="department"> Повторите пароль: input type="password" name="password2" class="form-control password2" value="pass" placeholder="" /> small id="emailHelp" class="form-text text-muted"> Пароли должны совпадать small> label> div> form> div>
Code language: HTML, XML (xml)

Разметка CSS

Добавим CSS-класс для размещения иконки, позволяющей пользователю взаимодействовать с элементом формы INPUT.

.password-icon < float: right; position: relative; margin: -25px 10px 0 0; cursor: pointer; >
Code language: CSS (css)

События на Javascript

Затем добавим код JavaScript, который содержит событие click, контролирующее каждое взаимодействие пользователя с иконкой клавиши show и hide.

window.addEventListener("load", function( ) < // иконка для отображения пароля showPassword = document.querySelector('.show-password'); showPassword.addEventListener('click', () => < // элементы ввода типа пароля password1 = document.querySelector('.password1'); password2 = document.querySelector('.password2'); if ( password1.type === "text" ) < password1.type = "password" password2.type = "password" showPassword.classList.remove('fa-eye-slash'); > else < password1.type = "text" password2.type = "text" showPassword.classList.toggle("fa-eye-slash"); > >) >);
Code language: JavaScript (javascript)

Результат работы примера можно посмотреть по ниже.

Источник

Оцените статью