Place unchangeable elements both preceding and following an input field

At first glance, this question bears a striking resemblance to this specific one. However, the original poster indicated that it remains unanswered, prompting me to inquire about its feasibility and implementation. Here is what I aim to achieve:

I am seeking to place elements (such as text or icon images) both before and after an input field, positioned beside the input itself instead of being absolute at the end of the container like in the referenced post. The goal is to ensure these additional components remain immutable to the user while leaving the input value unaffected.

Here is an excerpt of my code:

const ProductPrice = () => {
  const [info, setInfo] = useState({
    discountPrice: '',
  });
  
  const handleChange = (e) => {
    const value = e.target.value
    setInfo({
      ...info,
      [e.target.name]: value
    })
  }

  return (
    <div className='price-container'>
      <input
        name='discountPrice'
        type='number'
        placeholder=''
        onChange={handleChange}
        value={info.discountPrice}
      />
    </div>
  );
};

Furthermore, here is a visual representation of the desired outcome: https://i.sstatic.net/UN7c2.png

Answer №1

It's important to note that simply adding a colored icon into the value of an input is not easily achievable. Using background images may work, but positioning the right-hand icon can be challenging.

At some point, you may need to improvise or find a workaround for displaying the input as desired.

One solution could be to create a label that resembles an input field, containing all necessary elements inside it. As the user types, the input within the label expands:

// https://stackoverflow.com/questions/3392493/adjust-width-of-input-field-to-its-input
var input = document.querySelector('input'); // get the input element
input.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
resizeInput.call(input); // immediately call the function

function resizeInput() {
  this.style.width = this.value.length + "ch";
}
.looks-like-input{
  border: 1px solid #ccc;
  background: #f5f5f5;
  padding: 30px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-radius: 5px;
}
.looks-like-input input{
  background: transparent;
  border: none;
}
<label for="text" class="looks-like-input">
  $
  <input type="text" id="text" />
  <svg width="20" height="20">
    <circle cx="10" cy="10" r="10" fill="green"></circle>
    <rect x="5" y="5" width="10" height="10" fill="#fff"></rect>
  </svg>
</label>

In my experience, making minor design changes can result in a more reliable front end. I recommend avoiding unnecessary modifications to input resizing unless absolutely necessary.

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

What is the best location to place an HTML wrapper element within a React Project?

Just diving into the world of React, I've embarked on a simple project with bootstrap My goal is to reuse a specific HTML structure: <div className="container"> <div className="row"> <div className="col-lg-8 col-md-10 mx-auto"&g ...

Discovering the most recent 10 date elements in a JSON object within a React application

I have an array of objects containing a date element. My goal is to identify the 10 most recent dates from this element and display them in a table format. When I attempt to render these dates using a mapping technique that targets each data with data.date ...

Tips for incorporating jQuery val() into a span element!

I am currently working on a plugin that involves interacting with select elements grouped within a span. I want to enhance the functionality of my plugin by adding support for the val() function, which will allow users to easily get or set the 'value& ...

unable to interpret information

I've encountered an issue with posting data to my webpage (page3.php). Despite using $test=$_POST['radio_second']; on the page, the test variable remains empty. Any help in resolving this would be greatly appreciated. Thank you! <p> ...

Tips for showcasing beautifully formatted XML content on a webpage

I have some XML data that I want to display on my website, but I'd prefer to show it in a styled format like a bootstrap table. However, I'm not sure how to go about doing this. Here's an example of the XML: <?xml version="1.0" encoding ...

Unique background image that perfectly aligns with the dimensions of a single full screen

Does anyone know how this webpage achieves the effect of having a full-screen background that ends when scrolling down? I have noticed that the picture of the desert always covers my entire browser screen but is not a typical full-screen background as it ...

issue with animation occurs when the value changes while the setTimeout timer is still running

function wallpaperMediaPropertiesListener(event) { // reset animation test.stop(true); test.css('margin-left', 0); // set song title. test.text(event.title); var testWidth = test.outerWidth(); // clone text ...

React doesn't store the `Session` `Cookie` in memory

I have encountered an issue with React not saving the Cookie in the cookie storage of my site. The API is running on Flask and has the following settings: # ------------- Flask App ------------- app = Flask(__name__, static_folder='templates/static& ...

Steps for resolving the CSS problem with the dynamic jquery category filter

I have developed a dynamic jquery category filter, but when I choose an option, the search results page displays content with unwanted spaces between them. It seems like there is excessive distance between each piece of content. $(document).ready(functi ...

Reduced resolution decreases image size significantly (bootstrap-5 Fluid)

What's Currently Happening: While using the Chrome browser's device toolbar tool to test my site at various resolutions, I observed that when I shrink the device screen to "Mobile-s" 320px, the content on my page becomes nearly unreadable. Additi ...

Cover the entire screen with a solid background color and adjust the text size accordingly

I'm encountering two issues. Despite my efforts to adjust multiple containers, the background colour #eee simply won't reach the bottom of the screen. I've even tried setting the HTML height to 100%, but to no avail. Even though I&apos ...

Help with Material-UI: Passing unique props to a custom TreeItem component

I am trying to pass an argument category to the component CustomTreeItem which uses TreeItemContent. Documentation: https://mui.com/ru/api/tree-item/ import TreeItem, { TreeItemProps, useTreeItem, TreeItemContentProps, } from '@material-ui/lab ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

React-router route does not activate

Apologies if this issue has been raised before, but I am new to react-router and unsure of what to ask. My current project involves creating a sidebar component for my app, which consists of material-ui drawer and list items. Each list item is linked using ...

Use the Segoe UI typeface on Internet Explorer for a sleek

I have implemented a custom Segoe UI font in my CSS file. While it displays correctly in Chrome, I am facing an issue where IE and Firefox are showing the default font in certain areas. Below is the snippet of the CSS code: body { margin:0px auto; ...

The function fs.readFileSync does not exist in the context of Meteor and React

Hey there, I'm encountering an issue in Chrome debugger where it says 'fs.readFileSync is not a function' when I try to use readFileSync(); This is how I set it up... const fs = require('fs'); I then proceeded to execute the fun ...

React's useState hook is not correctly updating the state variables when the form is submitted

const [user, setuser] = useState({ name: '', lastName: '', pass: '', mail: '', uName: '' }) const [nameError, setNameError] = useState(''); const [lastNameError, setLastNameError] = useState( ...

Automatically populate email fields with pre-filled form data

Looking to create an HTML form that utilizes JS/jQuery (no PHP) to capture data from "subject" and "message" fields and send an email. The goal is for the client-side code to open the user's mail client, pre-fill the subject and body with form data, a ...

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...