Type to add a prefix or suffix

Seeking assistance with adding a prefix/suffix to text input as it is typed, without the ability to delete the added characters. The final string cannot consist solely of the prefix/suffix.

Any suggestions for a plain JavaScript solution?

EDIT:

I need help implementing this feature for a username input field, where a specific prefix/suffix is required. Currently using a static label at the start/end and combining strings, but looking for a more visually appealing method. Any ideas that do not involve pop-up messages or validations?

Answer №1

Changing user input on keypress is a definite anti-pattern! There are numerous scenarios where this approach falls short and becomes challenging to work with... When the user types quickly, when content is pasted, or if the event is triggered by a non-typing key.

A potentially better solution, in my humble opinion (IMHO), is to link user input with a read-only modified input (or another UI element)!

<input id="rkjv" type="text">value<br/><br/>

<input id="up" type="text">up<br/><br/>
<input id="down" type="text" readonly>down<br/><br/>

let userInput = document.getElementById('rkjv')

let prefix='@'
let suffix='%'

function adjustInput(el){
  let originalVal = el.target.value;
  if(originalVal!==''){
      let adjustedVal = originalVal
    if(!adjustedVal.match(new RegExp('^' + prefix))){
        adjustedVal = prefix + adjustedVal
    }
    if(!adjustedVal.match(new RegExp(suffix + '$'))){
        adjustedVal = adjustedVal + suffix
    }
        if(adjustedVal!==originalVal){
        el.target.value = adjustedVal
    }
  }
}

userInput.onkeyup = adjustUserInput

/* :] */

function adjustOutput(el){
    let userOutput = document.getElementById('down')
  let originalVal = el.target.value;
  let adjustedVal = originalVal

  if(adjustedVal !== ''){
      adjustedVal = prefix + adjustedVal + suffix
  }
  userOutput.value = adjustedVal

}


let userInputUp = document.getElementById('up')
userInputUp.onkeyup = adjustOutput

Take a look at how not to do it in this terrible implementation
https://jsfiddle.net/6f5zgtqo/5/

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

Is your Jquery validation malfunctioning?

I am currently facing a challenge with required validation on an asp.net page. In order to validate the inputs, I have implemented multiple controls which can be hidden or displayed based on certain conditions. These controls include checkboxlists, dropdow ...

"Node.js mystery: Why does a function call return undefined, only to be evaluated

Utilizing the async module, I am running a series of functions in parallel. However, I have encountered an issue where the return value of another function is undefined because the callback does not wait for it to be evaluated. function getGenresId(genres ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

What is the most effective method for displaying error messages in Extjs?

I am currently using the store.synch() method to post data, with validation being done on the server side. I am currently displaying error messages in a message box, but I want to explore alternative ways to show errors without having to use markInvalid( ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Is the auto-import feature in the new VSCODE 1.18 compatible with nodelibs installed via npm?

Testing out the latest auto-import feature using a JS file in a basic project. After npm installing mongoose and saving an empty JS file for editing, I anticipate that typing const Schema = mongoose. will trigger an intellisense menu with mongoose nodelib ...

JavaScript powered caller ID for web applications

I am currently working on an innovative project where I aim to automatically detect the phone number of a landline call to a specific device. While research led me to various packages like npm caller-id-node that work with desktop applications using the mo ...

switching the color of a path in an SVG when hovering over a

In the midst of working on SVG, I'm trying to implement a color change effect upon hover. The desired functionality is such that when hovering over the .business div, the color of the SVG business path should also change accordingly as specified in th ...

Avoiding HTML in JavaScript: Tips and Tricks

My application generates numerous elements dynamically based on server data in JSON format. This process involves embedding a significant amount of HTML directly within my JavaScript code, leading to pollution and making it increasingly challenging and l ...

Node Js issue stemming from unaddressed promises leading to rejection

Hi, everyone! I'm currently facing some challenges while trying to deploy this API. The error message I keep getting is: "UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error may have occurred due to either throwing inside an asyn ...

What are the steps for integrating a date and time picker bootstrap plugin?

Referencing a tutorial from http://www.w3schools.com/bootstrap/bootstrap_modal.asp: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <div id="myModal" class="modal fade" role= ...

Issue with Three.js: GLTF model not positioned correctly at origin point

After attempting to load a glTF model with a 0,0,0 position, I noticed that it appears far from the origin. Upon trying to rotate the glTF model, I observed that it spins around (indicated by blue dots) the origin instead of spinning from its center. Thi ...

What is the best way to integrate a loop in JavaScript to retrieve values?

<script> var data={ Data: { name: 'aaaa', number: '0003' }, values: { val: '-20.00', rate: '22047' }, user: [ '6|1|5', '10|1|15' ] }; ...

Converting a class-based component into a functional component

TL;DR : I am in the process of converting my class-based App component to a Functional component but encountering unexpected outcomes with the useEffect Hook. Being relatively new to React, I originally built my movie search app using a class-based approa ...

Eliminate the blank choice from X-editable Select

Lately, I've been dealing with AngularJS and X-editable and one thing that has been troubling me is the fact that the select option always includes an empty first child. Here's the HTML <span editable-select="curuser.roles" e-name="roles" ...

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

Main.js in Electron cannot find the NODE_ENV environment variable

Currently, I am in the process of developing an application which involves: React 16.4.0 Electron 2.0.2 Webpack 4.11.0 After successfully compiling and running the app using webpack (webpack dev server), my focus now shifts to showing only Chr ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

How can TypeScript and MobX work together using Set()?

I'm encountering errors while trying to implement Set() in my Grocery Shopping app using MobX with TypeScript. I have a simple setup with defined types in types.ts: types.ts export type Item = { name: string; instock: number; price: number; }; ...