Add a symbol at the end of the input that signifies its value

I have a form field that expects a percentage as input, but I want to visually indicate to the user that they should enter a percent value.

The challenge I face is that I want the percentage symbol to appear before the number in the input box, like this: 100% or 10000%, without actually being part of the input value.

Is there a way to achieve this? I've experimented with CSS options, but so far I haven't been able to get the percentage symbol to align with the input value dynamically. It always stays at the end of the input field instead of adjusting its position based on the input length.

The input component code looks like this:

class Input extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isActive: false,
    }
  }

  render() {
    return (
    <div>
      <input 
        value={this.props.value} >
      </input>
    </div>
    )
  }
}

CSS snippet:

div {
  input:after {
    content: '%';
    position: absolute;
    top: 3.4rem;
    z-index: 9999;
    color: blue;
    font-size: 2rem;

  }
}

This example demonstrates what I'm aiming for - the user should be able to edit the highlighted text while the percentage symbol dynamically adjusts its position based on the input length:

https://i.sstatic.net/jCfvQ.png

https://i.sstatic.net/VBrNh.png

Answer №1

One simple solution is to utilize the data-attribute within a container (as input does not support :before and :after, see [More here]) along with CSS content: attr()

update = function(el) {
  el.parentElement.setAttribute('data-value', el.value)
}
div[data-value] {
  position: relative;
}
div[data-value]:after {
  content: attr(data-value) "%";
  position: absolute;
  top: 2px; /* Borders */
  left: 2px; /* Borders */
}
div[data-value] input {
  color: #FFF; /* Optional bug avoid visual bugs */
}
<div data-value="0.01">
  <input value="0.01" oninput="update(this)"/>
</div>

Note: I implemented this in plain JavaScript, but it can be easily adapted for use in React.

Answer №2

Here is a simple solution using jQuery:

$("#input").on("keyup", function(){
  $(this).val($(this).val().replace(/[^0-9]/gi, '') + '%')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input"/>

This code snippet adds a % sign at the end of the input and only allows numbers to be entered.

If desired, this functionality can also be implemented in regular Javascript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Navigating to the appropriate section by clicking on a navbar item with Bootstrap 5: A step-by-step guide

Hi everyone! I am just starting out in front-end development and I was hoping to get some clarification on a topic. I need to create a one-page website where the navigation bar links scroll down to the correct sections when clicked. It's all on one pa ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

After making a POST request, the `Req.body` is assigned to

This is the JavaScript code I am using: app.use(express.static(__dirname)); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // support json encoded bodies app.get('/', function(req, res){ res.sendFile(__dirn ...

Scraping a p tag lacking a class attribute with the help of BeautifulSoup4 (Bs4)

I am attempting to scrape this information from a website: enter image description here Within the HTML, there is a div tag with a class. Inside that div tag, there is another div tag and then a lone p tag without a class. My objective is specifically to ...

The Silent Signin functionality on Casdoor seems to be experiencing issues and is not functioning

I am currently working on a solution to streamline the login process for users across all my applications, and we have decided to implement Casdoor for this purpose. While experimenting with oAuth2, I encountered an issue where logging into the first app w ...

Creating an array of form input names using JavaScript within the HTML input tag

I have a two part question that I'm hoping someone can help me with. There was a similar question asked recently that included information about this particular type of array in PHP, but unfortunately, I can't seem to locate it at the moment. 1. ...

Switching from dark mode to light mode when reloading or navigating to a new page

Hello everyone. I've successfully implemented a dark mode toggle on my website, but I'm facing an issue where the mode resets whenever I navigate to a new page or refresh the current page. Can anyone help me figure out how to prevent this from ...

Having trouble toggling webcam video in React/NextJS using useRef?

I have created a Webcam component to be used in multiple areas of my codebase, but it only displays on load. I am trying to implement a toggle feature to turn it on and off, however, I am facing difficulties making it work. Below is the TypeScript impleme ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

What is the best way to shift <p> slightly to the left using css?

I've created an HTML file structured like this. <html> <head> </head> <body> <div class="final_time"> <p class="final_time_text">some text here</p> </div> </b ...

When the user clicks, show a designated search result in a separate container

I've been developing my Angular cocktail application, and I've reached a point where I can display all the cocktails in my database (only showing names). Now, I want to implement a feature where if I click on a specific cocktail, its full content ...

Is there a way to customize the CSS ul menu specifically for the JavaScript autocomplete feature?

I have created a search page with autocomplete for the first textbox, but I noticed that the ul/li CSS classes used for styling the main menu are impacting the JavaScript list. How can I override the menu styling to display a regular list format? Being a ...

What is the process of converting a file into a binary stream using Javascript?

I'm currently in the process of building a website using Next.js and I want to upload a file to OneDrive using the Microsoft Graph REST API. The documentation states that the request body should be the binary stream of the file you wish to upload, bu ...

Tips on displaying a successful message and automatically refreshing the page simultaneously

I am working on a JSP Servlet code that utilizes AJAX to handle user data. In the success function of AJAX, I aim to display a success message to the user and clear all fields in the form by reloading the page. Unfortunately, when the page reloads, the a ...

Checking the validity of user input statements

When 2 conditions are met, both error links and messages will display on top of each other. If an input is 0, the validation statement for empty inputs will also trigger. Additionally, if one input is not numeric but the other is, PHP will calculate the va ...

How can I ensure that every dependency in my package.json is updated to the newest version using Yarn?

My current react app is using deprecated dependencies and in order to get it functional, I need to update these dependencies to more recent (yet stable) versions. According to a discussion on Stack Overflow, for updating dependencies in package.json to th ...

Enhance form validation by utilizing jquery.validate to display appropriate icons indicating correct and incorrect input, with the option to

Trying to replicate the functionality of the jQuery validate plugin demo seen here, I am facing an issue on my own website. Upon clicking submit after the page loads, the plugin displays validation messages with a cross symbol. However, upon entering text, ...

Z-index malfunctioning - need to troubleshoot

Check out my website at Upon visiting the website on a PC, you'll notice that the navigation menu appears on the loader. Can anyone explain why this is happening? The only modifications I made to my CSS are: <style> .navbar-inverse { backg ...