I have 3 different password input as:
--Current Password Input
<input asp-for="ChangePassword.OldPassword" id="currentPassword" required autofocus />
<button type="button" id="toggleCurrentPassword" tabindex="99"><i ></i></button>
--New password input
<input asp-for="ChangePassword.NewPassword" id="newPassword" required autofocus />
<button type="button" id="toggleNewPassword" tabindex="99"><i ></i></button>
--Confirm password input
<input asp-for="ChangePassword.ConfirmPassword" id="confirmPassword" required autofocus />
<button type="button" id="toggleConfirmPassword" tabindex="99"><i ></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
CodePudding user response:
You could create a function to handle each eventListener:
function passwordToggle(button, input) {
$(button).click(function() {
if ($(input).attr('type') === "password") {
$(input).attr('type', 'text');
} else {
$(input).attr('type', 'password');
}
})
}
passwordToggle('#toggleCurrentPassword', '#currentPassword');
passwordToggle('#toggleNewPassword', '#newPassword');
passwordToggle('#toggleConfirmPassword', '#confirmPassword');