Check if DOM Element is a checkbox - javascript

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.

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")) {
}

Checks anything
function isCheckbox (element) {
return element instanceof HTMLInputElement
&& element.getAttribute('type') == 'checkbox'
}

if( $(element)[0].type == "checkbox" ) {
}
OR
if( $(element).is(':checkbox') ) {
}

Take a look at the checkbox selector.
var checkboxes = $("form input:checkbox");
You can tell what type an input is like this:
if ($(".your-input").is(":text"))
{
// Textbox
}
else if ($(".your-input").is(":checkbox"))
{
// Checkbox
}

if (<DOMNode>.type === "checkbox") {
// ...
}

Try this;
$(element).is(':checkbox');
here element is selector to your element
if( $(element).is(':checkbox') ) {
// do something
}

jQuery is():
if ($el.is(':checkbox')) { ... }

You can use the pseudo-selector :checkbox with a call to jQuery's is function:
$('#myinput').is(':checkbox')

You should have a decent naming convention which allows you to know if an element is a checkbox from just seeing it's id or name.
e.g. "chkMyCheckbox"

Related

Disable every non checked checkbox

I have a bunch of forms with a checkbox in each of them and when a condition is met i want to disable every checkbox that is NOT checked.
I've tried doing this but with no luck
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]:not(:checked)').disabled = true;
}
I would preferably only use vanilla javascript.
querySelectorAll returns a NodeList object, you have to use that object to iterate through the elements and disable them.
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach((element) => {
element.disabled = true;
});
}
You can use something like this:
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]').forEach(i => i.disabled = true);
}
Edit: I was too slow. Already suggested by #Gunther: https://stackoverflow.com/a/65692054/4261813
You will need to loop through the results of querySelectorAll.
if (updateShowcasedProducts.length == 12) {
els = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
for (const el of els) {
el.disabled = true;
}
}
You can first use a class for all those inputs what are checkboxes. And then use checked property:
let checkBoxes = document.getElementsByClassName("checkbox");
checkBoxes.forEach(checkBox)=>{
if(!checkBox.checked){
checkBox.disabled=true;
};
});

Fetch specific element using custom attribute in jQuery

Below is a sample structure from which i'm trying to get the specific value of custom attribute
<div id="123"></div>
<div id="456"></div>
<div context="james"></div>
Below is how i'm trying to fetch, but it always returns false.
if ( $('div').attr('context') == 'james' ) {
alert("yes");
} else {
alert("no");
}
The call to $('div').attr('context') will only grab the first div found in the DOM and check it's value. Since it doesn't have that attribute you get false. Instead you will want to iterate over all your div's and check each one. For example:
var found = false;
$('div').each(function( ) {
if($(this).attr('context') === 'james') found = true;
});
if(found) alert("yes");
else alert("no")
You could also use .filter:
if( $('div').filter(function(){ return $(this).attr('context') === 'james' }).length )
alert("yes");
else
alert("no");
Note: If you used data-context="james" you would use the .data() method rather than .attr().
Simply let jQuery do the filtering for you. Also, this can be done with plain old vanilla javascript pretty easily:
// Select by attribute
var theDiv = $("div[context='james']");
// If we have something here...
if(theDiv.length){
console.log(theDiv.text() );
} else {
console.log("Nope, not found.");
}
// We can use this same selector with plain javascript...
let theSameDiv = document.querySelector("div[context='james']");
// In this event, however, we access the text differently.
if(theSameDiv){
console.log("Found without jQuery!", theSameDiv.textContent);
} else {
console.log("Rats...");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="123">the first div</div>
<div id="456">div the second</div>
<div context="james">I'm 'Enry the Eighth, I Am!</div>

jQuery check if class exists or has more than one class

I have a class js-bootstrap3 that is generated by a cms. What I need to do is check if the containing element just has js-bootstrap3and .unwrap() the contents, but if the element has multiple classes which include js-bootstrap3 then I'm trying to just remove that class.
jsFiddle
$('.jsn-bootstrap3').each(function(){
if( $(this).attr('class') !== undefined && $(this).attr('class').match(/jsn-bootstrap3/) ) {
console.log("match");
$(this).contents().unwrap();
$(this).removeClass('jsn-bootstrap3');
}
});
This just seems to detect any element with js-bootstrap3as a class and unwraps it.
this.className is a string with all of the classes for the element (space delimited), so if it's not just "jsn-bootstrap3" you know it has more than one class:
$('.jsn-bootstrap3').each(function(){
if( $.trim(this.className) !== "jsn-bootstrap3") {
// Just jsn-bootstrap3
$(this).contents().unwrap();
} else {
// More than just jsn-bootstarp3
$(this).removeClass('jsn-bootstrap3');
}
});
Dependeing on the browsers you need to support element.classlist (IE10+) might or might not be what you need.
classList returns a token list of the class attribute of the element.
classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className. It contains the following methods:
Otherwise you're looking at splitting the className into an array like so to count the values:
var classes = element.className.split(" ");
Building on your example you could do something liket his:
$('.jsn-bootstrap3').each(function(i, el){
if( el.className.indexOf('jsn-bootstrap3') != -1 ) {
console.log("match");
if ( el.className.split(" ").length > 1 ) {
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
}
});
Try this code.
$(document).ready(function(){
$('.jsn-bootstrap3').each(function(){
var classes = $(this).attr('class');
var new_cls = classes.split(' ');
if( new_cls.length > 1 ){
$(this).removeClass('jsn-bootstrap3');
} else {
$(this).contents().unwrap();
}
});
});

How do I check if value is empty?

I have a few select menus that include blank options. When both are blank (usually on the first page load), I would like to show some hidden div.
This is what I have:
$('.variant_options select').each(function() {
if ($(this).attr('value') === '') {
// some code here to show hidden div
console.log("No options chosen");
}
});
This doesn't seem to work.
Edit 1
For what it's worth, I have tried something like this:
if (!$(this).attr('value'))
And that has seemed to work, but it breaks functionality elsewhere.
<select> elements don't have a value attribute, so you need to use .val() on the element to find out if the currently selected option is empty.
if ($(this).val() === '') {
// value of select box is empty
}
this.value === '' should also work
To check whether no options are selected:
if (this.selectedIndex == 0) {
// no option is selected
}
You can do so by using the following:
if($(this).val() === '') {
// value is empty
}
I believe also the following too:
if(!$(this).prop('value')) {
// It's empty
}
You can simply do this:
$('.variant_options select').each(function () {
if ($.trim($(this).val()) === '') {
// some code here...
}
});
jQuery can check for value by using $(this).val()
So you would do if ($(this).val === '')`
If you wanted to check for some other attribute, like href or src, you could do
if ($(this).attr('href') === ''
In case if you have spaces, use this trick:
if ($.trim($(this).val()) === '') { ...

is an element an input?

How can you check if an element is an input?
if(elm.val() == null){
// is not an input
}
else{
// is an input
}
Well you know what element you are selecting.
or (if you really do not know) you can do:
if(elm.is('input')) {} //assuming elm is a jQuery element
else {}
You can use the is function to determine if an element is an input tag:
jQuery(elm).is("input");
//jquery
if( $("#elementid").is("input") ){}
else
{}

Categories