Pull to refresh

JavaScript & JQuery 1.8.3 генератор пароля

Предисловие

Совсем недавно решил написать генератор пароля с возможностью просмотра генерированного пароля под звездочками. Для работы выбрал JQuery 1.8.3 и нативный JavaScript. При написании самого скрипта столкнулся с проблемой в JQuery 1.8.3 с функцией attr().

Вот сама проблема

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
...
<script>
$('.showPassword').click(function(){
	var inputPsw = $('#password');
	if (inputPsw.attr('type') == 'password'){
         	inputPsw.attr('type', 'text');
	} else {
        	inputPsw.attr('type', 'password');
        }
});
</script>
...
<input type="password" name="password" id="password" />
<a href="#" class="showPassword">Показать</a>


Вид в консоли:… type property can't be changed

Проблема в том, что в JQuery 1.8.3 есть небольшой косяк, функция attr() не работает по замене свойства атрибута, т.к. защита браузеров блокируют ее. В версии JQuery 1.9.0 она исправлена.

Решение

Нашел такое вот решение на нативном JavaScript с помощью хардкора и функции .setAttribute(name, value) — устанавливаемый атрибут.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
...
<script>
	$('.showPassword').click(function(){
		var inputPsw = $('#password');
		if (inputPsw.attr('type') == 'password') {
			document.getElementById('password').setAttribute('type', 'text');
		} else {
			document.getElementById('password').setAttribute('type', 'password');
		}
	});
</script>
...
<input type="password" name="password" id="password" />
<a href="#" class="showPassword">Показать</a>


Сам скрипт генерации пароля с возможностью просмотра генерированного пароля под звездочками


...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
//Скрипт генерации паролей
	function str_rand() {
		var result       = '';
		var words        = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
		var max_position = words.length - 1;
			for( i = 0; i < 10; ++i ) {
				position = Math.floor ( Math.random() * max_position );
				result = result + words.substring(position, position + 1);
			}
		return result;
	}
	$('.showPassword').click(function(){
		var inputPsw = $('#password');
		if (inputPsw.attr('type') == 'password') {
			document.getElementById('password').setAttribute('type', 'text');
		} else {
			document.getElementById('password').setAttribute('type', 'password');
		}
	});
	$('.generatePassword').click(function() {
		document.getElementById('password').setAttribute('type', 'text');
		$('#password').attr('value', str_rand());
	});
});
</script>
....

<input type="password" name="password" id="password" />
<a href="#" class="showPassword">Показать</a>
<a href="#" class="generatePassword">Сегенерировать</a>
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.