Frosted Cupcake
Frosted Cupcake

Reputation: 1970

How to add a permanent label beside entered text in an input field in React

I have an input field in my application and I need to place a permanent label beside entered text in that input field. Also, the styles of the label to be placed are different from that of the entered text. Something like as shown below, Label of KMs placed beside entered text

I tried replicating the behavior here. I am able to place a label beside the entered text, but I want the label to also move forward as the characters are being typed in the input box. Currently, my entered text comes on top of the label placed, as shown below- Label overlapping with entered text

I found a similar question here, but in the suggested answer, the label doesn't move with the entered text.

How can I achieve this behavior? Thanks a lot in advance!

Upvotes: 0

Views: 1538

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21485

Styling the label differently from the input is what makes this especially challenging; they'll need to be different DOM nodes, so simpler solutions like input masking will not be sufficient.

You'll need to scale the width of the input based on its content; one way would be to use a normal <input> field and resize it via javascript on every keystroke.

Alternatively, you could use a contentEditable element with display: inline-block to automatically handle the layout; then when you're ready to do something with that value you can read its innerHTML. A simple demonstration is below:

getvalue = () => {
  console.log(document.getElementById('input').innerText)
}
.fake_form_input {
  border: 1px solid;
  paddding: 0.2em;
}

#input {
  display: inline-block;
  min-width: 1em;
  padding: 0.2em;  
  outline: none;

}

.label {
  display: inline-block;
  color: red;
}
<div class="fake_form_input">
  <div contenteditable id="input">0
  </div>
  <div class="label">KM</div>
</div>

<button onclick="getvalue()">Go</button>

(Note that this introduces some a11y issues, you'll want to add some ARIA tagging etc if you use this technique)

Upvotes: 2

Pulse
Pulse

Reputation: 214

Give it a try:

const myInput = document.getElementById('inp');
const inputLable = document.querySelector('.inputContainer span');


myInput.addEventListener('keydown', handleLable)

function handleLable(element) {
    const charLength = element.target.value.length;
    
    inputLable.style.left = charLength * 9 + 20 < myInput.clientWidth - 40 ? charLength * 9 + 20 + "px" : myInput.clientWidth - 30 + "px";
    
}
.inputContainer{
    position:relative;
  width:300px;
}

.inputContainer span{
    position:absolute;
    left:16px;
  top:50%;
  transform:translateY(-50%);
  color: red;
}

#inp{
    width: 100%;
    padding-right: 48px;
    font-size: 16px;
  
}
<div class="inputContainer">
    <input type="text" id="inp" />
    <span>KMs</span>
</div>

Upvotes: 2

Related Questions