I have an input field type password, I'm trying to put show / hide icon inside it. The problem is the icon, it is actually another input field and with html I can't put an input field inside another input field.
Can someone help me ? Maybe with css there can be a solution? Sorry but I'm not very good with this, I appreciate any answer, thanks.
function showPassword() {
var x = document.getElementById("password_current");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
/*Toggle Password class*/
#togglePw { display: none; }
#togglePw label:before { content: "\f06e"; }
#togglePw:checked label:before { content: "\f070"; }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<p >
<label for="password_current"></label>
<input type="password" name="password" id="password_current" autocomplete="off"/> <input type="checkbox" id="togglePw" onclick="showPassword()"/>
<label for="togglePw" ></label>
</p>
CodePudding user response:
I would suggest using absolute positioning to align the icon.
Wrap the two inputs (password & checkbox) in a div.
<div id="password-input-toggle">
<input id="your-password-field"/>
<input type="checkbox" id="your-toggle-checkbox"/>
</div>
#password-input-toggle {
position: relative;
}
#your-toggle-checkbox {
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
}
CodePudding user response:
Just use some CSS to nudge it left a little, not forgetting to allow for padding on the input control so text won't cover it.
function showPassword() {
var x = document.getElementById("password_current");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
/*Toggle Password class*/
#togglePw {
display: none;
}
#togglePw label:before {
content: "\f06e";
}
#togglePw:checked label:before {
content: "\f070";
}
/* add these: */
#togglePw label {
position: relative;
left: -30px;
cursor: pointer;
}
#password_current {
padding-right: 30px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<p >
<label for="password_current"></label>
<input type="password" name="password" id="password_current" autocomplete="off" /> <input type="checkbox" id="togglePw" onclick="showPassword()" />
<label for="togglePw" ></label>
</p>