is it possible to make a default value in input field of html and that value is not editable, after that we can add some value in it.. Ex: fist two characters are 'AB' is a default and not editable and after that we can add any numbers in same input field AB6382826 like this, can we make using java script, can anyone help?
CodePudding user response:
You may listen for the user input on your input
field and always prepend AB
to whatever the user has typed. You'd also need to apply in way you don't get redundant text in that field so we should always remove AB
before prepending it once again to prevent redundancy.
Here's a live demo:
const inp = document.getElementById('my-input'),
/** the text to prepend, store it in a variable and use it whenever needed */
textToPrepend = 'AB',
/** the regular expression that will help us prepend the text by deleting the prepended text each time the user types in the field */
prependRegEx = /^(AB?)?/;
/** listen for user input on the field and prepend the text as needed */
inp.addEventListener('input', () => inp.value = textToPrepend (inp.value == textToPrepend ? '' : inp.value.replace(prependRegEx, '')))
<input type="text" value="AB" id="my-input">
Even though the above demo works as expected, the validation in the backend is highly recommended as i can use
JS
to send a value that doesn't respect your format.
CodePudding user response:
make the use of "Maskedinput.js" in the jquery lib
CodePudding user response:
Try to use Maskedinput.js, or something like that in Jquery library or imaskjs for vanilla javascript.
CodePudding user response:
You can fetch the input value on each input and use String.padStart method, like so:
const inputVal = 'something';
const newVal = inputVal.padStart(inputVal.length 2, 'AB');
console.log(newVal);
Expected output: ABsomething
CodePudding user response:
Putting AB
inside a label
and using position:absolute
to place it inside the input
& using padding-left
on input for making the space for the label text.
inside the js i am doing the samething that @catfish
did by getting the value entered by the user and doing padStart()
on it to my initial characters i.eAB
.
i am displaying the result inside the h1.
function show(event) {
event.preventDefault();
let inputVal = document.querySelector("#input").value;
let newVal = inputVal.padStart(inputVal.length 2, 'AB');
document.querySelector("#input").value = "";
document.querySelector(".preview").textContent = `Your Value Is: ${newVal}`;
}
* {
font-family: monospace;
margin=0;
padding=0;
box-sizing: border-box;
}
.wrapper {
position: relative;
}
#label {
font-size: 16px;
color: gray;
position: absolute;
top: 50%;
left: 4px;
transform: translateY(-50%);
}
#input {
color: gray;
padding-left: 25px;
font-size: 16px;
}
<form onsubmit="show(event)" >
<label id="label" for="input">AB</label>
<input type="text" id="input" placeholder="Enter to Submit">
</form>
<h1 ></h1>