Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript how to tell that element is checkbox, so element.checked is not red underlined

I am checking for input type of some element, fe checkbox in TS. Now I am sure that I have element that is checkbox, so this element should have property checked. But if I simply do

element: HTMLElement
if (element.InputType.toLowerCase() == "checkbox"){
    element.checked = true;
}

than it is working, but element.checked is red underlined. I think that I simply have to retype from HTMLElement to something like CheckboxElement, but did not find anything suitable for this conversion. How to get rid of this ? I have facing this also in case of element.value

like image 253
Petr Krčmárik Avatar asked Oct 20 '15 16:10

Petr Krčmárik


People also ask

How do you check if a checkbox is checked or not in TypeScript?

To check if a checkbox element is checked in TypeScript: Type the element as HTMLInputElement using a type assertion. Use the checked property to see if the element is checked. The property will return true if it is checked and false otherwise.

How do you verify checkbox is checked or not?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.

What is checkbox value if not checked?

If the checkbox has the required attribute, but is not checked, then ValidityState.valueMissing will be true .


2 Answers

There is no "checkbox" element type as it is just an "input" element with type checkbox. You could use/assert with the type HTMLInputElement which is an extension of HTMLElement:

var element: HTMLInputElement;
//... You still need to do all the null checks as necessary
//The below check may be irrelevant depending upon what you are actually doing. 
//But i am just adding here to show that you need to refer to the property "type" and 
//not "InputType"
if (element.type.toLowerCase() == "checkbox") { 
     element.checked = true;
}
like image 168
PSL Avatar answered Nov 10 '22 00:11

PSL


The if statement is not necessary as others have already stated. However, there are several ways how to make compiler happy:

// 1st (best variant in my opinion)
let e1: HTMLInputElement; // type of variable
e1.checked = true;

// 2nd (sometimes a good option too)    
let e2 = document.getElementById('myInput');
(<HTMLInputElement>e2).checked = true; // "hint" the type to TypeScript

// 3rd (a hack that may come handy sometimes)
let e3 = document.getElementById('myInput');
e2['checked'] = true;
like image 26
Martin Vseticka Avatar answered Nov 10 '22 00:11

Martin Vseticka