Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if DOM Element is a checkbox

How can I check if a given DOM element is a a checkbox.

Scenario:

I have a set of textboxes and checkboxes in which the values are assigned dynamically. I don't have a way to identify if the DOM element is a checkbox or a textbox.

like image 949
Nipuna Avatar asked Jun 20 '12 08:06

Nipuna


People also ask

Which method is used to check the status of checkbox?

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.

How do you check a checkbox in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.

How do you check checkbox is checked or not in TS?

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 check if checkbox is checked jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


2 Answers

Using only vanilla javascript you could do

if (el.type && el.type === 'checkbox') {    ... } 

or even shorter

if ((el || {}).type === 'checkbox') {    ... } 

or in modern browsers you could use matches()

if (el.matches('[type="checkbox"]') {     ... } 
like image 89
Fabrizio Calderan Avatar answered Sep 18 '22 09:09

Fabrizio Calderan


If you're using jQuery, you can use the :checkbox pseudo-class selector along with is method:

if($("#that-particular-input").is(":checkbox")) { } 
like image 36
Salman A Avatar answered Sep 21 '22 09:09

Salman A