Reputation: 419
Currently I have my HTML below in 2 different areas of our app to toggle classes .icon-eye-open
& .icon-eye-close
for 2 different input fields.
The issue is when the user clicks on the .icon-eye-close
button both input fields get reveled to show passwords when I only need one input field to get revealed.
Side note: The input fields are generated in python.
What's the best way to execute this?
HTML:
<button type="button" class="show-password-toggle icon-eye-close icon-align-confirm"></button>
JS:
$('.show-password-toggle').each(function () {
var eye = $(this);
eye.on('click', function() {
eye.toggleClass("icon-eye-open icon-eye-close");
eye.siblings("input").each(function () {
if (eye.hasClass('icon-eye-open')) {
$(this).attr('type', 'text');
}
else if (eye.hasClass('icon-eye-close')) {
$(this).attr('type', 'password');
}
});
});
});
Generated python code:
<input type="text" name="password2" minlength="6" placeholder="Confirm password" id="id_password2">
and
<input type="text" name="password2" minlength="6" placeholder="Confirm password" id="id_password2">
Thanks
Upvotes: 3
Views: 3548
Reputation: 8605
You are using each
to iterate the matched inputs, so yes, you're doing it for both.
You could simply split them up, so there is they are no longer siblings. For example:
<div>
<button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">aaa</button>
<input type="text" value="bbb">
</div>
<div>
<button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">bbb</button>
<input type="text" value="bbb">
</div>
Alternatively, use a more specific selector, like id
.
/*
This is the exact same JS used by the OP
*/
$('.show-password-toggle').each(function () {
var eye = $(this);
eye.on('click', function() {
eye.toggleClass("icon-eye-open icon-eye-close");
eye.siblings("input").each(function () {
if (eye.hasClass('icon-eye-open')) {
$(this).attr('type', 'text');
}
else if (eye.hasClass('icon-eye-close')) {
$(this).attr('type', 'password');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">Toggle first</button>
<input type="password" value="bbb">
</div>
<div>
<button type="button" class="show-password-toggle icon-eye-close icon-align-confirm">Toggle second</button>
<input type="password" value="bbb">
</div>
Upvotes: 5