Как открыть текст в инпуте с type=password?
Привет.
Есть инпут: <input type=password> соответственно когда вводим текст в это поле, он маскируется символом: * Как с помощью javascript показать текст закрытый звездочками в поле с "type=password"? Пробовал динамически заменить type у инпута с password на text, но естественно это ничего не изменило. Как можно осуществить задуманное или это вообще невозможно сделать? |
не работает только в IE
подменять на input type="text" c value от input type="password" |
Почему то не работает такой код:
function ShowHidePassword(id) { element = document.getElementById(id); if element.type == 'password' { element.type = 'text' } else { element.type = 'password' } } В HTML следующий код: <input type="password" id="pid"> <a href="#" onclick="ShowHidePassword('pid')"> Текст введенный в поле не показывается. По прежнему остаются символы * |
в IE только и не работает
|
Kotakota,
<script> function ShowHidePassword(id) { element = document.getElementById(id); if (element.type == 'password') { /*element.type = 'text'; element.value = element.value;*/ var inp = document.createElement("input"); inp.id = id; inp.type = "text"; inp.value = element.value; //alert(inp.parentNode.tagName); element.parentNode.replaceChild(inp, element); } else { /*element.type = 'password'; element.value = element.value;*/ var inp = document.createElement("input"); inp.id = id; inp.type = "password"; inp.value = element.value; element.parentNode.replaceChild(inp, element); } } </script> <input type="password" id="pid"> <a href="#" onclick="ShowHidePassword('pid')">click</a> |
<input type="password"> <input style="display: none;"> <input type="button" value="show/hide"> <script> window.onload = function () { function f(el1, el2) { el2.style.display = 'inline'; el1.style.display = 'none'; el2.value = el1.value; } var els = document.body.children; els[2].onclick = function () { if (navigator.userAgent.indexOf('MSIE') != -1) { if (els[1].style.display != 'inline') { f(els[0], els[1]); } else { f(els[1], els[0]) } return; } if (els[0].getAttribute('type') != 'text') {// els[0].setAttribute('type', 'text'); } else { els[0].setAttribute('type', 'password'); } } } </script> либо через insertAdjacentHTML |
Благодарю за ответы!
|
Нахрена только мудрить с проверкой на ие - непонятно.
|
Цитата:
решение со сменой type всё же логичнее и проще и не подходит только для IE<9, поэтому основывать решение изначально на костыле имхо не гуд, потом только удалить кусок костыльного кода |
В конечном итоге с использованием JQuery получилось так:
<script language="Javascript"> function ShowHidePassword(id){ element = $('#'+id) element.replaceWith(element.clone().attr('type',(element.attr('type') == 'password') ? 'text' : 'password')) } </script> |
Цитата:
|
Если поддержка IE8 не нужна, то:
<!DOCTYPE html> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" /> <style> input{ vertical-align: middle; font-family: "Lucida Console", Monaco, monospace; } input::-ms-reveal, input::-ms-clear { display: none; } .password-reveal{ border: none; padding: 0; width: 1.3em; height: 1.2em; margin-left: -1.9em; vertical-align: middle; background: none; color: #555; cursor: default; } .password-reveal:hover{ color: #222; } </style> <span class="input-wrap"> <input type="password" value="password" /> <button tabindex="-1" aria-hidden="true" class="password-reveal" type="button"><span class="fa fa-eye"></span></button> </span> <script> (function() { var eye = document.querySelector('.password-reveal'); eye.onmousedown = function() { return false; }; eye.onclick = function() { var input = this.previousElementSibling; var selection = {start: input.selectionStart, end: input.selectionEnd}; input.type = {text: 'password', password: 'text'}[input.type]; input.selectionEnd = selection.end; input.selectionStart = selection.start; return false; }; })(); </script> |
Цитата:
<style> img { position: relative; width: 1em; height: 1em; top: 0.2em; left: -1.5em; z-index: 100; } </style> <input type="password" value="something wrong"> <img src="http://www.wordassociations.ru/image/600x/svg_to_png/Anonymous_eye.png"> <script> (function () { var input = document.querySelector("input"); document.querySelector("img").addEventListener("click", function () { if (input.getAttribute('type') != 'text') { input.setAttribute('type', 'text'); } else { input.setAttribute('type', 'password'); } }); })(); </script> |
bes, а почему атрибуты вместо свойств?
Кстати, заметил, что map выглядит выразительней, чем тернарный оператор: input.type = {text: 'password', password: 'text'}[input.type]; input.type = input.type == 'text' ? 'password' : 'text'; Или мне одному так кажется? |
danik.js,
мысли вслух ... input.type = input.type != 'text' ? 'text':'password' ; с "неравно" конструкция надёжнее и сработает например при смене стиля display по умолчанию или придётся добавить ещё '' : 'none' и вариант использования ))) <style> span { cursor: pointer; } </style> <span class="test"></span> <script> (function() { function wordReplace(elem, first, last) { var word = {}; word[first] = last; word[last] = first; elem.innerHTML = first; elem.onclick = function() { elem.innerHTML = word[elem.innerHTML] } } var test = document.querySelector('.test'); wordReplace(test, 'первый', 'второй') })(); </script> |
Цитата:
ещё более вероятно, что отстал в развитии, так как не понял на основе чего ты это провернул Цитата:
|
Ну в IE8 этот код в любом случае не работает ) Ну а насчет Chrome надеюсь ошиблись. Иначе это печально.
Цитата:
Или в чем проблема? Кажется способ не очень выразительный ) |
Цитата:
|
Цитата:
причём сбил с толку Цитата:
|
Цитата:
|
Цитата:
|
Ну вы запарились!
Пожизненно вот так делаю onkeyup('{this.title=this.value}') и все довольны до опупения. Подвел мышь - посмотрел (пока никто не видит), убрал мышь - никто не видит. Для мобильных предлагаю просто давать вводить без буллетов и все. |
Так в личку мне и не отвечают=( напишу сюда.
У меня в файле вот такой код там: <tr> <td class="simplecheckout-login-left"><?php echo $entry_password; ?></td> <td class="simplecheckout-login-right"><input type="password" name="password" value="" /></td> </tr> Что мне в нем поменять получается? |
Leanidas, в html вставляй кнопку глаза, в css - стили для глаза, в js - код для глаза.
Все это бери отсюда: #12 Только не тяни весть font-awesome ради одной иконки. |
Все настроил!! Всем спасибо большое!!
А еще последний вопрос как сделать так что бы глаз у меня был на уровне слова поля и с правой стороны - вот моя страница регистрации - http://unikross.ru/index.php?route=a...simpleregister |
для ИЕ
<html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <style>body {} </style> </head> <body> <form> <input type="password" id="fld4" name="pass" size="50" maxlength="80" /> </form> <input id="a" type="button" class="button" value="Посмотреть" onclick="pas()" /> <script> $("#a").click(function () { var frm = $('form:first'); alert(frm.serializeArray()[0].value); }); </script> </body> </html> |
WTF???
Deff, ты где пропадал? Лечился? Кажется недолечился.. |
Цитата:
|
danik.js,
Болел, родственников с Киева вывозил, потом в ополчении бодался(точнее топталсо в окружении замов стрелка, узнавал что-почем и к чему движемся.. потом послал всё нах, ибо там масса интересов, далёких от чаяний после Крыма) |
А как сделать если два паса?
и нужно что б переводило в text сразу два поля? |
Часовой пояс GMT +3, время: 11:13. |