Below Jquery is working fine but How could I shorten this Jquery? I have to show and hide the password for password and confirmed password? https://jsfiddle.net/c5cvLo54/1/
$(".password-showhide .show-password").click(function() {
$("#password").attr("type", "text");
$(".password-showhide .show-password").hide();
$(".password-showhide .hide-password").show();
});
$(".password-showhide .hide-password").click(function() {
$("#password").attr("type", "password");
$(".password-showhide .hide-password").hide();
$(".password-showhide .show-password").show();
});
$(".confirm-password-showhide .show-password").click(function() {
$("#confirmPassword").attr("type", "text");
$(".confirm-password-showhide .show-password").hide();
$(".confirm-password-showhide .hide-password").show();
});
$(".confirm-password-showhide .hide-password").click(function() {
$("#confirmPassword").attr("type", "password");
$(".confirm-password-showhide .hide-password").hide();
$(".confirm-password-showhide .show-password").show();
});
Here is one-of-the ways, how you can shorten your code:
$(document).ready(function() {
$(".show-password, .hide-password").on('click', function() {
var passwordId = $(this).parents('li:first').find('input').attr('id');
if ($(this).hasClass('show-password')) {
$("#" + passwordId).attr("type", "text");
$(this).parent().find(".show-password").hide();
$(this).parent().find(".hide-password").show();
} else {
$("#" + passwordId).attr("type", "password");
$(this).parent().find(".hide-password").hide();
$(this).parent().find(".show-password").show();
}
});
});
li {
list-style: none
}
.hide-password {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<input type="password" name="password" id="password" />
<span class="password-showhide">
<span class="show-password">Show</span>
<span class="hide-password">hide</span>
</span>
<li>
<li>
<input type="password" name="password" id="confirmPassword" />
<span class="confirm-password-showhide">
<span class="show-password">Show</span>
<span class="hide-password">hide</span>
</span>
<li>
</ul>