How to put Show / Hide Icon inside input field - javascript

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 class="">
<label class="t2" for="password_current"></label>
<input type="password" class="field-settings" name="password" id="password_current" autocomplete="off"/> <input type="checkbox" id="togglePw" onclick="showPassword()"/>
<label for="togglePw" class="fa"></label>
</p>

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%);
}

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 class="">
<label class="t2" for="password_current"></label>
<input type="password" class="field-settings" name="password" id="password_current" autocomplete="off" /> <input type="checkbox" id="togglePw" onclick="showPassword()" />
<label for="togglePw" class="fa"></label>
</p>

Related

Removing input label when typing

I have an input field that I cannot use a placeholder for, instead I must use a label and place it as it was a placeholder, so right in the field. How can I hide the label when you start typing into the field, and make the label reappear hen all letters are removed from the field - so just like the placeholder ould behave?
My html:
<label class="PR_label" for="PR">My label</label>
<input type="hidden" name="PR" value="" id="TR">
EDIT: I realised this is not possible since my input field is hidden and you cannot enter/type anything since there is no fied to begin with.
You can place the label inside the textbox using position: absolute; and then hide the label when the user types, using an event listener:
var textbox = document.getElementById("input_box")
var label = document.getElementById("label")
textbox.addEventListener("keydown", function() {
label.style.display = "none"
}, false);
#input_box {
position: absolute;
top: 0;
left: 0px;
}
#label {
position: absolute;
top: 0;
left: 0px;
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<input value="" id="input_box">
<label id="label">Lorem ipsum</label>
<script src="code.js"></script>
</body>
</html>
If you want use your label as placeholder in your input field you can use CSS position.
* {
box-sizing: border-box;
}
.form-control {
width:50%;
padding: 0.625rem;
position: relative;
}
label {
position: absolute;
top: 1.7rem;
right: 1.625rem;
color: blue;
}
input[type="text"] {
display: block;
width: 100%;
padding: 1rem;
}
<div class="form-control">
<label class="PR_label" for="PR">test</label>
<input type="text" name="PR" value="a" id="TR">
</div>
HTML:
<div class='wrapper'>
<label class="PR_label" for="PR">My label</label>
<input type="hidden" name="PR" value="" id="TR">
</div>
If you plan to make it visible again:
const labelElement = document.querySelector('.PR_label')
const inputElement = document.querySelector('input')
inputElement.addEventListener('keydown', () => {
labelElement.style.display = 'none'
})
If you plan to not make it visible again:
const labelElement = document.querySelector('.PR_label')
const inputElement = document.querySelector('input')
inputElement.addEventListener('keydown', () => {
labelElement.remove()
})
css:
.wrapper {
display: grid;
grid-template: 1fr / 1fr;
}
input,
.PR_label {
grid-row: 1;
grid-column: 1;
}
Make use of a placeholder inside your input and also don't forget to add alternative keys for accessibility checks.
WITH PLACEHOLDER
<input id="TR" class="text" type="text" name="PR" value="" placeholder="PR" alt="PR">
WITHOUT PLACEHOLDER
Using jQuery
$(".input").each(function () {
var inputVal = $(this).val();
$(this)
.focus(function (event) {
if (this.value == inputVal) {
this.value = "";
}
})
.blur(function (event) {
if (this.value == "") {
this.value = inputVal;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="Example Value" class="input">

Remove html label tag text when value is entered - with CSS

So i'm trying to remove the label and its value from my input html tag whenever the person enters a value, and the code that I have right now does the job but it only removes the value when I click on the input box. Once I enter a value the label is stuck there along with the value of the input. Can someone help me make it so the label is removed completely not just when it's clicked on. And is this something I can do with css? if I can't then how would I do it with javascript?
.text-input-wrapper {
position: relative;
}
.text-input-wrapper label {
position: absolute;
left: 0;
}
.text-input-wrapper label::before {
transition: 0s;
}
.text-input-wrapper label.icon1::before {
content: 'Email';
}
.text-input-wrapper label.icon2::before {
content: 'Password';
}
.text-input-wrapper input {
padding: 0 2rem 0;
}
.text-input-wrapper input:focus+label::before,
.text-input-wrapper input:active+label::before {
display: none;
}
<form class="clearfix credentials-form login-form" method="POST">
<div class="credentials-form__fields">
<div class="text-input standard login-text-input login-email">
<div class="text-input-error-wrapper">
</div>
<div class="text-input-wrapper">
<input type="email" id="login_email2812380460348143" class="text-input-input" name="login_email" value="" autocomplete="off" aria-invalid="false" inputmode="text">
<label for="login_email2812380460348143" class="icon1"></label>
</div>
</div>
<div>
<div class="tooltip-container">
</div>
<div class="text-input standard login-text-input login-password">
<div class="text-input-error-wrapper">
</div>
<div class="text-input-wrapper">
<input type="password" id="login_password5101720956289264" class="text-input-input password-input" name="login_password" value="" autocomplete="off" aria-invalid="false" inputmode="text">
<label for="login_password5101720956289264" class="icon2"></label>
</div>
</div>
</div>
</div>
<button class="login-button signin-button button-primary" type="submit">
<div class="signin-text">Sign in
</div></button>
</form>
Try this way...
const inputs = document.querySelectorAll('.text-input-wrapper input');
const labels = document.querySelectorAll('.text-input-wrapper label');
inputs.forEach((input, i) => {
input.addEventListener('input', () => {
labels[i].style.opacity = 0;
});
});
Use an onInput event instead of an onChange one.

Issue with JS form submission

This is with regard to an ongoing question asked previously. I am trying to make a contact form to work using HTML, CSS and JavaScript. All my conditions seem to be working fine. The issue here is that whenever I fail to enter a particular field, and later re-enter it, the error message is still being displayed. Also, I want the user to be redirected to another HTML page once he clicks on Submit and once all conditions are satisfied. I would like some guidance on the same. Herewith attaching the code for reference.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register with us</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body style="position: relative;">
<div class="container"> <br>
<h1 class="text-center">Register with Us!</h1>
<form>
<div class="form-group">
<label for="fname" id="firstname">First name: </label>
<input type="text" class="form-control" id="fname" placeholder="Enter your first name">
<small id="firstnameerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="lname" id="lastname">Last name: </label>
<input type="text" class="form-control" id="lname" placeholder="Enter your last name">
<small id="lastnameerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="emailid" id="emailaddress">Email address:</label>
<input type="email" class="form-control" id="emailid" aria-describedby="emailHelp"
placeholder="Enter email">
<small id="emailerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="pass1" id="password1">Password: </label>
<input type="password" class="form-control" id="pass1" placeholder="Enter a password">
<small id="passerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="confirmpass" id="password2">Confirm Password: </label>
<input type="password" class="form-control" id="confirmpass" placeholder="Re-enter password">
<small id="passerror2" class="form-text"></small>
</div>
<div class="form-group">
<label for="phno" id="ctno">Contact number : </label>
<input type="number" class="form-control" id="phno" placeholder="Enter your number here">
<small id="phoneerror" class="form-text"></small>
</div>
<button type="submit">Submit</button>
</form>
</div>
<script src="/js/vaildate.js"></script>
</body>
</html>
#firstnameerror,
#lastnameerror,
#emailerror,
#passerror,
#phoneerror{
color: tomato;
font-size: 1.1em;
margin-left: 10%;
margin-top: 2.5%;
}
#firstname,#lastname,#emailaddress,#password1,#password2,#ctno{
padding: 0.7em;
font-size: 1.3em;
font-family: 'Noto Sans', sans-serif;
font-weight: 600;
text-align: center;
color: white;
margin-left: 9%;
}
#fname,#lname,#emailid,#pass1,#confirmpass,#phno{
margin: 0.3em 0.7em;
width: 80%;
font-family: 'Poppins', sans-serif;
margin-left: 10%;
background-color: black;
border: none;
padding: 1em;
border-radius: 2em;
color: white;
}
.container{
margin-top: 20vh;
background-image: linear-gradient(to right, rgb(46, 46, 46) , rgb(20, 20, 20));
border-radius: 5em;
}
.container h1{
color: white;
}
button{
margin-left: 10%;
margin-top: 2.5%;
font-size: 1.4em;
padding: 0.5em 1em;
font-family: 'Open Sans', sans-serif;
border-radius: 1.2em;
outline: none;
border: none;
background-color: teal;
color: white;
font-weight: bold;
}
const form = document.querySelector(".container");
const firstname = document.getElementById("fname");
const lastname = document.getElementById("lname");
const emailid = document.getElementById("emailid");
const password = document.getElementById("pass1");
const confirmpassword = document.getElementById("confirmpass");
const phoneno = document.getElementById("phno");
// Function to check if first name is entered properly
function checkfname(fname) {
let letters = /^[A-Z]+[a-z]+$/;
if (fname.match(letters)) {
document.getElementById("firstnameerror").innerHTML.style = "none";
return fname;
}
else {
document.getElementById("firstnameerror").innerHTML = "Please enter the details accurately";
return false;
}
}
// Function to check if first name is entered properly
function checklname(lname) {
let letter = /^[A-Z]+[a-z]+$/;
if (lname.match(letter)) {
document.getElementById("firstnameerror").innerHTML.style = "none";
return lname;
}
else {
document.getElementById("firstnameerror").innerHTML = "Please enter the details accurately";
return false;
}
}
//function to check if the password is entered properly
function passcheck(pass) {
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if (pass.match(paswd)) {
document.getElementById("passerror").innerHTML.style = "none";
return pass;
}
else {
document.getElementById("passerror").innerHTML = "Entered password does not meet the requirements";
return false;
}
}
function phonecheck(phval) {
var phonecheck = /\+?\d[\d -]{8,12}\d/;
if (phval.match(phonecheck)) {
document.getElementById("phoneerror").innerHTML.style = "none";
return phval;
}
else {
document.getElementById("phoneerror").innerHTML = "Please enter a valid phone number";
return false;
}
}
// Function to check if all parameters have been entered
function testfunc() {
if (firstname.value == "") {
document.getElementById("firstnameerror").innerHTML = "Please enter your first name";
}
else {
firstname.value = checkfname(firstname.value);
}
if (lastname.value == "") {
document.getElementById("lastnameerror").innerHTML = "Please enter your last name";
}
else {
lastname.value=checklname(lastname.value);
}
if (emailid.value == "") {
document.getElementById("emailerror").innerHTML = "Please enter your E-mail ID";
}
else {
document.getElementById("emailerror").innerHTML.style = "none";
}
if (password.value == "") {
document.getElementById("passerror").innerHTML = "Please enter a password";
}
else {
password.value=passcheck(password.value);
}
if (confirmpassword.value == "") {
document.getElementById("passerror2").innerHTML = "Enter the password again"
}
else if (confirmpassword.value == password.value) {
document.getElementById("passerror2").innerHTML.style = "none";
document.getElementById("passerror").innerHTML.style = "none";
}
else {
document.getElementById("passerror2").innerHTML = "Passwords do not match";
}
if (phoneno.value == "") {
document.getElementById("phoneerror").innerHTML = "Please enter your mobile number";
}
else {
phoneno.value = phonecheck(phoneno.value);
}
}
form.addEventListener("submit", function (e) {
e.preventDefault();
testfunc();
}
)
If I were you, I would add event listeners (on change) for each of the inputs. Then save the value of those inputs to variables and clear the error message of that particular input. This way makes the most sense to me from a user experience perspective.
As for the submit function's redirect, just use one of the ways W3Schools suggests:
// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com")
Also,
document.getElementById("firstnameerror").innerHTML.style = "none";
wont work. What you're looking for is probably either clearing the text:
document.getElementById("firstnameerror").innerHTML = "";
Or hiding the element itself:
document.getElementById("firstnameerror").style.display = "none";
.style = "none" won't work.
.style.display = "none" is probably what you want.
Also, you can probably do everything (or nearly everything) of what you're checking in Javascript via HTML form validation as well, e.g. required attribute.

Make Anchor tag work conditionally using Javascript

I have a Radio button. I want to implement a validation on "Submit" Anchor tag that displays an error if no selection is made on the radio button and redirects to the URL provided in the href attribute if the radio button selection is made.
Below is the code for radio button -
<div>
<input required="" type="radio" id="group02-0" name="group02" value="Yes" onclick="yesnoCheck();">
<label for="group02-0" >Yes</label>
<input type="radio" id="group02-1" name="group02" value="No" onclick="yesnoCheck();">
<label for="group02-1">No</label>
</div>
<script>
var radio_value = "";
function yesnoCheck() {
radio_value = document.querySelector('input[name="group02"]:checked').value;
}
</script>
In the same HTML file, I have code for the Submit Anchor tag -
<span>Submit</span>
<script>
function submitCheck() {
if (radio_value === "") {
//Display an error. The user should not be taken to the next page
return false;
} else {
//User should be taken to the URL in the href attribute
return true;
}
}
</script>
Irrespective of whether I make a selection on the radio button, the anchor tag always takes me to the next page. Please help!
You don't need two radio buttons. Only one Checkbox.
Use Event.preventDefault() to prevent default browser navigation
Use the input element's checked state to determine the outcome
Finally use document.location to navigate to a EL_submitBtn.getAttribute('href')
PS: Don't use inline JavaScript (in HTML). JS should be in one place and that's your JS file or inside a <script> tag. It's easier to debug and maintain.
Single checkbox
const EL_submitBtn = document.querySelector('#submitBtn');
const EL_acceptCkb = document.querySelector('[name="accept"]');
function submitCheck(ev) {
ev.preventDefault(); // prevent follow link
if (!EL_acceptCkb.checked) { // Unchecked
alert("You will not get a better UX");
} else { // Checked
alert("Yes! Buckle up!")
document.location = EL_submitBtn.getAttribute('href');
}
}
EL_submitBtn.addEventListener('click', submitCheck);
<div>
<h3>Would you like a better UX?</h3>
<label>
<input type="checkbox" name="accept"> Yes I do
</label>
</div>
<a id="submitBtn" href="https://www.google.com">Submit</a>
Two radio buttons
Use document.querySelector('[name="accept"]:checked') to get the checked one, if any.
const EL_submitBtn = document.querySelector('#submitBtn');
function submitCheck(ev) {
ev.preventDefault(); // prevent follow link
const EL_acceptCkd = document.querySelector('[name="accept"]:checked');
if (!EL_acceptCkd) { // None checked
alert("You must select Yes or No.");
} else if (EL_acceptCkd.value === 'no') { // "NO" checked
alert("You will not get a better UX");
} else { // "YES" checked
alert("Yes! Buckle up!")
document.location = EL_submitBtn.getAttribute('href');
}
}
EL_submitBtn.addEventListener('click', submitCheck);
<div>
<h3>Would you like a better UX?</h3>
<label>
<input type="radio" name="accept" value="yes"> Yes
</label>
<label>
<input type="radio" name="accept" value="no"> No
</label>
</div>
<a id="submitBtn" href="https://www.google.com">Submit</a>
use css pointer-events: none; -> https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
If you absolutely want to use button radios (even if it's a bit twisted as an idea) here is the code:
const aHrefGoogle = document.getElementById('aHrefGoogle');
document.querySelectorAll('input[name=group02]').forEach(el=>
{
el.onchange=_=>{ if (el.checked) setLinkOnOff(el.value) }
})
function setLinkOnOff(val)
{
if (val==='yes') { aHrefGoogle.classList.remove('adisableHref') }
else { aHrefGoogle.classList.add('adisableHref') }
}
.adisableHref {
color: grey;
pointer-events: none;
cursor: default;
text-decoration-line: none;
}
make link Google active ?
<label ><input type="radio" name="group02" value="yes">Yes </label>
<label ><input type="radio" name="group02" value="no" checked>No! </label>
<br><br>
<span> Google </span>
for memo here is the initial code with a checkbox :
const yesnoCheck = document.getElementById('yesnoCheck')
, aHrefGoogle = document.getElementById('aHrefGoogle')
;
// init
yesnoCheck.checked = false
aHrefGoogle.classList.add('adisableHref')
yesnoCheck.oninput =_=>
{
if (yesnoCheck.checked) { aHrefGoogle.classList.remove('adisableHref') }
else { aHrefGoogle.classList.add('adisableHref') }
}
#yesnoCheck { display: none; }
#yesnoCheck + label { display: inline-block; background: #cd3c3c; color: white; padding: .17em .2em; cursor: pointer; }
#yesnoCheck:checked + label { background: #378b2c; }
#yesnoCheck + label::before { content: 'NO'; display: inline-block; width:2.6em; text-align: center; }
#yesnoCheck + label::after { content: ''; display: inline-block; width:0; text-align: center; }
#yesnoCheck:checked + label::before { content: ''; width:0; }
#yesnoCheck:checked + label::after { content: 'YES'; width:2.6em; }
.adisableHref {
color: grey;
pointer-events: none;
cursor: default;
text-decoration-line: none;
}
make link Google active ?
<input type="checkbox" id="yesnoCheck"><label for="yesnoCheck">▉</label>
<br><br>
<span> Google </span>

How to make an input field readonly based on anther input field?

I am making a unit converter with two input fields, one for centimeters and the other for inches. I was wondering if it would be possible for one of the fields to be changed to read only if there is input in the other field. Here is my code for one of the fields:
<input name="cm" class="inputs peach Calibri" type="number" min="0" step="1" />.
Any help would be appreciated. Thanks!
This would be a fairly good starting point.
let cmInput = document.getElementById("cminput");
let inInput = document.getElementById("inchinput");
cmInput.onkeyup = function(){
if(cmInput.value !== ""){
inInput.disabled = true;
}else{
inInput.disabled = false;
}
};
inInput.onkeyup = function(){
if(inInput.value !== ""){
cmInput.disabled = true;
}else{
cmInput.disabled = false;
}
};
<input type="text" placeholder="centimetres" id="cminput">
<input type="text" placeholder="inches" id="inchinput">
Not the cleanest way but it works just add your logic for conversion. This also remove readonly attr when input field is empty
jsfiddle (click me)
<label for="cm">cm: </label>
<input name="cm" id="cm" class="inputs peach Calibri" type="number" min="0" step="1" />
<label for="inch">inch: </label>
<input name="inch" id="inch" class="inputs peach Calibri" type="number" min="0" step="1" />
$('#cm').on('keyup', function() {
if ($('#cm').val() != '') {
$('#inch').prop('readonly', true);
} else if ($('#cm').val() == '') {
$('#inch').prop('readonly', false);
}
});
$('#inch').on('keyup', function() {
if ($('#inch').val() != '') {
$('#cm').prop('readonly', true);
} else if ($('#inch').val() == '') {
$('#cm').prop('readonly', false);
}
});
would you consider another pattern for this?
The readonly solution is pretty straigh forward, but a lot of sites with not only numeric convertion, for example, google translate, use a button to switch the convertion leaving the right side of the converter control with a read only, so if you want to make something like this in order to follow a more standart pattern
here it is
$('button').on('click',function(){
$('.cont').toggleClass('invert')
});
$('input').on('keypress',function(){
if($('.cont').hasClass('invert')){
// some convertion code for INCH to CM
}else{
// some convertion code for CM to INCH
}
});
.cont{
display:flex;
align-items: center;
justify-content: center;
border:1px solid silver;
}
.cont.invert{
flex-direction: row-reverse;
}
fieldset{
border:none;
position:relative;
}
button{
display: block;
line-height: 22px;
}
.cont.invert fieldset:first-child:after{
content:"";
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top:0px;
background-color: rgba(255,255,255,.3);
}
.cont.invert fieldset:last-child:after{
display: none;
}
.cont fieldset:last-child:after{
content:"";
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top:0px;
background-color: rgba(255,255,255,.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<fieldset>
<label for="inp1">CM</label>
<br>
<input type="text">
</fieldset>
<button>
< >
</button>
<fieldset>
<label for="inp1">INCH</label>
<br>
<input type="text">
</fieldset>
</div>
As you can see, i did not disabled the input, i used a block to cover it from editing, the block on top of the right input has a white background with alpha on it, this way, if you want, you can control the way of the "disabled" one, no touching the input´s css and may looks the same on every browser.
Hope this helps
You could call a js function oninput like so:
<input type="text" id="cm" oninput="input('cm')"/>
<input type="text" id="inch" oninput="input('inch)"/>
function input(which){
if(which === 'cm'){
if(document.getElementById('cm').value!= ''){
document.getElementById('inch').disabled = true;
}else{
document.getElementById('cm').disabled = false;
}
}else{
if(document.getElementById('inch').value!= ''){
document.getElementById('cm').disabled = true;
}else{
document.getElementById('inch').disabled = false;
}
}
}

Categories