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.
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.
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.
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.
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);
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"]') { ... }
If you're using jQuery, you can use the :checkbox
pseudo-class selector along with is
method:
if($("#that-particular-input").is(":checkbox")) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With