I have 3 different password input as:
--Current Password Input
<input asp-for="ChangePassword.OldPassword" class="form-control" id="currentPassword" required autofocus />
<button class="btn btn-light shadow-none ms-0" type="button" id="toggleCurrentPassword" tabindex="99"><i class="mdi mdi-eye-outline"></i></button>
--New password input
<input asp-for="ChangePassword.NewPassword" class="form-control" id="newPassword" required autofocus />
<button class="btn btn-light shadow-none ms-0" type="button" id="toggleNewPassword" tabindex="99"><i class="mdi mdi-eye-outline"></i></button>
--Confirm password input
<input asp-for="ChangePassword.ConfirmPassword" id="confirmPassword" class="form-control" required autofocus />
<button class="btn btn-light shadow-none ms-0" type="button" id="toggleConfirmPassword" tabindex="99"><i class="mdi mdi-eye-outline"></i></button>
As you can see each one have a button, when user click I remove the type password, and if the user click again I add it again.
My script to do that:
$('#toggleCurrentPassword').click(function() {
if ($('#currentPassword').attr('type') === "password") {
$('#currentPassword').attr('type', 'text');
} else {
$('#currentPassword').attr('type', 'password');
}
})
$('#toggleNewPassword').click(function() {
if ($('#newPassword').attr('type') === "password") {
$('#newPassword').attr('type', 'text');
} else {
$('#newPassword').attr('type', 'password');
}
})
$('#toggleConfirmPassword').click(function() {
if ($('#confirmPassword').attr('type') === "password") {
$('#confirmPassword').attr('type', 'text');
} else {
$('#confirmPassword').attr('type', 'password');
}
})
It is working, but I think it should be a better way to do this, there is a lot of repeated code in function. How can I do a better work here? Regards
2
Answers
You could create a function to handle each eventListener:
In my opinion, you could simply create a function to be reusable, I think.
Example: