Home > Blockchain >  Removing input label when typing
Removing input label when typing

Time:05-04

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  for="PR">My label</label>
  <input type="hidden" name="PR" value="" id="TR">

CodePudding user response:

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>

CodePudding user response:

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 >  
  <label  for="PR">test</label>
  <input type="text" name="PR" value="a" id="TR">  
</div>

CodePudding user response:

HTML:

<div class='wrapper'>
  <label  for="PR">My label</label>
  <input type="hidden" name="PR" value="" id="TR">
</div>

If you plan to make it visible again:

let labelElement = document.querySelector('.PR_label')
let inputElement = document.querySelector('input')

inputElement.addEventListener('keydown', () => {
  labelElement.style.display = 'none'
})

If you plan to not make it visible again:

let labelElement = document.querySelector('.PR_label')
let 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;
}

Hope this helps!

CodePudding user response:

Make use of a placeholder inside your input and also don't forget to add alternative keys for accessibility checks.

<input id="TR"  type="text" name="PR" value="" placeholder="PR" alt="PR">

  • Related