How to fix a part of a value in a form field, leaving the user only the opportunity to add their own part, without erasing the preset value?

For example, in the field, I indicate the telephone code of the state, and the user only has to supplement it without being able to erase it.

    2 answers 2

    Somehow you can

    var prefix = '375-' var inputVal; $('#prefix').val(prefix); $('#prefix').on('keyup change', function(){ inputVal = $(this).val(); if(inputVal.substr(0, prefix.length) != prefix){ $(this).val(prefix + inputVal.substr(prefix.length-1)) } console.log(inputVal.substr(0, prefix.length)); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" id="prefix" /> 

    • Thank you, understand your idea! The truth still wanted to do so that the code could not even put the cursor. - Vitaly Komarov

    You can use the pseudo-class in which you enter the body. the state code (and also to tighten it with js with the necessary change), and in the text field itself, move the input area to the right. Instead of the vacated space, move the pseudo-class using positioning. And no js for such statics is needed.
    The same implementation is used if you need a picture (phone icon) in the text field to place for styling, this is done by simple positioning and a pseudo-class. Just to stylize the information entered in the form, you probably met something like that somewhere.

    In any situation, I recommend not to use js, if it is possible to implement using css.

    • I don’t know what a pseudo-class is, but the principle is clear, we will study. Thank. - Vitaly Komarov
    • @ Vitaliy Komarov, then it’s clear why you didn’t immediately think about him) Learn, it’s not long. - VostokSisters