3

I'm building a registration form in Angular 2 that asks a user to provide their website's URL before submitting.

When the form is submitted, I need the provided URL to be in the style of "http://www.google.com". To steer the user towards that format, I want the form field to autofill the initial "http://" as soon as the user clicks on the field (or when the user begins typing - either case would be acceptable). Currently I have placeholder text in the field that says "Please provide your website's URL", but I'm having trouble making the "http://" prefix appear when the user actually clicks on the field or starts typing.

Any ideas would be appreciated. Here is what the form field looks like when the user clicks on it. It's contents should switch to "http://" when clicked or typed in. Here is what the code looks like at the moment:

<div class="form-group">

  <input
    class="form-control"
    type="text"
    name="companyUrl"
    [(ngModel)]="user.companyUrl"
    placeholder="Company url"
    required pattern='https?://.+'
    #companyUrl
   >

    <div *ngIf="companyUrl.errors && (companyUrl.dirty || companyUrl.touched)" class="text-danger">
      <div [hidden]="!companyUrl.errors.required">
        Company URL is required.
      </div>
      <div [hidden]="!companyUrl.errors.pattern">
        URL should begin with http:// or https://
      </div>
    </div>

<div>

1 Answers1

0

Add a function to add the prefix on click event of the input. Something like below:

<input #companyUrl  (click)="addHttpPrefix()" >

And in this function 1. Get the value of companyUrl. 2. Check if it begins with http then skip else prepend with http://

if(companyUrl.indexOf('http') > -1) {
    companyUrl = 'http://' + companyUrl;
}

This way when the user initially clicks on the input http:// would be appended. if the (click) event does not meet your requirement you can try using (change) or other events.

Surender Khairwa
  • 601
  • 4
  • 17