There is a field:

<input id="box-1-form-input" type="text" name="box-1-form-input" placeholder="http://www." value="http://www." class="form-control"> 

It must be done so that it always defaults to " http: // www .". For myself, I identified 2 options:

  1. Using a mask library by type ( https://github.com/RobinHerbots/Inputmask )

  2. Manual filtering via regexp

In the first version I encounter a problem, since the mask needs to indicate the number of characters and as a result, the input field is " http: //www.___________________ ".

In the second version, I could not decide how to work with the input data without affecting my own mask (remove duplicate "http" and "www"). For example, sketched this code:

 $("#box-1-form-input").on('change keyup input', function() { var input = $(this); if(~input.val().indexOf("http://www.")) { // regexp } else { input.val("http://www."); } }); 

What do you advise?

  • What does it mean? The user is always seen or when sending added? If the first, then this is absurd. - user220409
  • @OlmerDale Alas, the first version - Happy_Cougar
  • Believe me, it will be very uncomfortable and not beautiful! If there is an opportunity, then refuse it. It's not hard to do, it's just terrible. - user220409
  • Does it bother you that there are sites that do not have the www prefix in the address? And if you add it there, the site will not open? And there are https: // sites, and they are getting more and more every day ... - Yaant
  • one
    Well, you set the default field value. It was highlighted on the screen. User interrupted him as he needed. What else is needed? On a fig, check it every time, if it can be completely different? If we allow someone to enter https://ru.stackoverflow.com will you let him go, replacing the input on http://www.ru.stackoverflow.com ? - Sergey

1 answer 1

Well, if I understand correctly, you can do it like this -

 class Input { constructor( input, prefix = '' ){ this.prefix = prefix; this.prefixLength = prefix.length; this.input = input; this.input.value = this.prefix; this.inputHandler = this.input_inputHandler.bind(this); this.input.addEventListener('input', this.inputHandler); } input_inputHandler( { target } ){ let { value } = target; if( value.length < this.prefixLength ){ target.value = this.prefix; } } } let input = new Input( document.body.querySelector('input'), 'https://www.' ); 
 <input type="text">