6

I am using typescript in my application.

html code:

<input type="text" name="lastname" id="last">

Typescript code:

let myContainer = <HTMLElement>document.getElementById('last');
myContainer.innerHTML = "";

I want to set the empty value for the last name field using typescript. I am using above code. But cannot able to add empty value using typescript.

I also tried by using below code:

document.getElementById('last').innerHTML = "";

How to assign empty value for the textbox using typescript?

4 Answers 4

6

Html input elements have the value property, so it should be:

let myContainer = document.getElementById('last') as HTMLInputElement;
myContainer.value = "";

Notice that I also used HTMLInputElement instead of HTMLElement which does not have the value property.

Sign up to request clarification or add additional context in comments.

Comments

4

You can also use it like this

const element: HTMLElement = document.getElementById('personDetails') as HTMLElement
element.innerHTML = 'Hello World'

Works in Typescript 2.0

Comments

1

You can use model value to bind to the element instead of using the id and inner html

Html code:

<input type="text" name="lastname" id="last" ng-model="innerHtml">

Typescript code:

let innerHtml :string = "";

OR

if you want to use the inner Html by id then you have to use this

TypeScript uses '<>' to surround casts Typescript code:

let element = <HTMLInputElement>document.getElementById("last");
element.value = "Text you want to give";

Comments

0

this is not a good practice, what we define in this way is not always the correct type.

let myContainer = document.getElementById('last') as HTMLInputElement;
myContainer.value = "";

or

const element: HTMLElement = document.getElementById('personDetails') as HTMLElement
element.innerHTML = 'Hello World'

if it is input use just HTMLInputElement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.