I have an initially empty input (text) field. I would like that as soon as someone begins to type (onkeypress??), a prefix/suffix will be autom. added to the typed string. It should not be possible to delete the prefix/suffix from the final string and it should not be possible that the final string is just the prefix/suffix (in this case the text field should be emptied).
Can someone help me with a (plain) javascript, please?
EDIT:
My use-case is very simple: the text field is used for defining a username. The user can choose whatever username he wants, but the rule says that the username must have a defined prefix/suffix. At the moment I put a fixed label at the start/end of the input field and than I concatenate the strings. It works fine but I find that visually is not optimal. I just thought that the other solution would be much cooler... Doing this with a validation and pop-up message is not an option.
It is definitely an anti-pattern to modify user input on keypress! There are many corner cases that make this annoying to use and hard to test... If the user types very fast, if content is actually copy-pasted, event being triggered by non typing keypress..
The "acceptable" solution IMHO
, if you really want this, is to correlate user input with a readonly modified input (or any other element on the UI)!
<input id="uazz" type="text">single<br/><br/>
<input id="in" type="text">in<br/><br/>
<input id="out" type="text" readonly>out<br/><br/>
let userInput = document.getElementById('uazz')
let prefix='@'
let suffix='%'
function transformInput(el){
let originalInput = el.target.value;
if(originalInput!==''){
let transformedInput = originalInput
if(!transformedInput.match(new RegExp('^' + prefix))){
transformedInput = prefix + transformedInput
}
if(!transformedInput.match(new RegExp(suffix + '$'))){
transformedInput = transformedInput + suffix
}
if(transformedInput!==originalInput){
el.target.value = transformedInput
}
}
}
userInput.onkeyup = transformInput
/* :] */
function transformInputOUT(el){
let userInputOUT = document.getElementById('out')
let originalInput = el.target.value;
let transformedInput = originalInput
if(transformedInput !== ''){
transformedInput = prefix + transformedInput + suffix
}
userInputOUT.value = transformedInput
}
let userInputIN = document.getElementById('in')
userInputIN.onkeyup = transformInputOUT
See for yourself on this horrible implementation
https://jsfiddle.net/6f5zgtqo/5/