Reputation: 114
I have several password inputs, but would like to toggle the password visibility via an icon (button), for each one. However, the following toggles all of them, and places the icon only on the first one.
Here's a fiddle: https://jsfiddle.net/bu6ysgsj/
$(function() {
$('.password-group').find('.password-box').each(function(index, input) {
var $input = $(input);
$('.password-visibility').click(function() {
var change = "";
if ($(this).find('i').hasClass('fa-eye')) {
$(this).find('i').removeClass('fa-eye')
$(this).find('i').addClass('fa-eye-slash')
change = "text";
} else {
$(this).find('i').removeClass('fa-eye-slash')
$(this).find('i').addClass('fa-eye')
change = "password";
}
var rep = $("<input type='" + change + "' />")
.attr('id', $input.attr('id'))
.attr('name', $input.attr('name'))
.attr('class', $input.attr('class'))
.val($input.val())
.insertBefore($input);
$input.remove();
$input = rep;
}).insertAfter($input);
});
});
.password-group {
position: relative;
width: 300px;
}
.password-group > input {
width: 100%;
}
.password-visibility {
position: absolute;
right: 8px;
top: 2px;
}
<div class="password-group">
<input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
<a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
<div class="password-group">
<input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
<a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
<div class="password-group">
<input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
<a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
<div class="password-group">
<input type="password" class="form-control password-box" aria-label="password" value="wdocechoiwceh98">
<a href="#!" class="password-visibility"><i class="fa fa-eye"></i></a>
</div>
Upvotes: 1
Views: 2593
Reputation: 20633
You click handler selector is too broad.
Change
$('.password-visibility').click(function() { ... })
to
$input.parent().find('.password-visibility').click(function() { ... })
JSFiddle demo: https://jsfiddle.net/bu6ysgsj/1/
Upvotes: 6