Check if checkbox has a class and is checked - javascript

I'm handling a checkbox.
if ($(this).hasClass("select")) { // To check class name
if ($(this).is(':checked')) { // to check whether it is checked
// some code
}
}
Now I have two if statements. How to merge them in a single condition?
I've tried:
1)
if ($(this).hasClass("select").is(':checked')) {
//statements
}
It gave me an error: .hasClass("...").is('...') is not a function.
2)
if ($(this).hasClass("select") && $(this).is(':checked')) {
// some code
}
else if ($(this).hasClass("select") && $(this).not(':checked')) {
// some code
}
It's working.
How to merge these two in single statement in a simplified manner? Can we simplify the condition?

You can do it by,
var cond = $(this).is(".select:checked");
var val = parseInt($(this).parent().next().text());
sum += (cond ? val : -(val));

You can move the class checking into .is():
if ($(this).is(".select:checked"))
$(this).hasClass("select").is(':checked') doesn't work because .hasClass() returns boolean, not the $(this) object, so you can't chain jQuery methods on it.

Related

How to check if a value exists in a select box using vanilla JS?

I want to create a function that accepts an argument of check that will loop through select box options and values and check to see if the value exists or not. I have it working (kinda) but it only checks the first option. If you run checkOption('red), you get an alert that Option Exists. However, if you run checkOption('green'), nothing happens.
I'm doing something simple here, but I can't figure it out. Thanks for any and all help.
Working CodePen:
CodePen
JavaScript:
let selectBox = document.querySelector("select");
let options = selectBox.querySelectorAll("option");
function checkOption(check) {
options.forEach((o) => {
if (o.value === check) {
return true; // returns undefined either way.
}
});
}
}
Edit: I am now able to get console.log() to print to the console, but I'm trying to return either True or False. How would I amend the above function to return True or False? So far, this only returns undefined.
You need to loop through the options in your function. You can also shorten by using forEach on the collection:
function checkOption(check) {
options.forEach( o => {
if( o.value === check) {
alert(`${check} is available`);
}
}
}
You could condense even more by using the array filter() function as well. You just need to make treat the options NodeList as an array but sticking it through the Array.from() method first:
function checkOption(check) {
if( Array.from(options).filter( o => o.value === check ).length )
alert(`${check} is available`);
}
or even shorter, let the function returns true or false to indicate the presence of the given option value.
function checkOption(check) {
return Array.from(options).filter( o => o.value === check ).length > 0;
}
You should use options.length in your loop. Besides that, it is good practice to define variables before using them. Your return statement should also be called immediately after a match is found to avoid unnecessary iterations, so you better include it in your if statement.
let selectBox = document.querySelector("select");
let options = selectBox.querySelectorAll("option");
function checkOption(check) {
for (var i = 0; i < options.length; ++i) {
if (selectBox.options[i].value === check) {
alert(`${check} is available`);
return;
}
}
}

How to check for attribute value

Please advise me if I am using correct syntax here for checking if “aria-expanded” is true for a particular set of elements with css class “classname”:
if ($(‘.classname’).hasAttribute('aria-expanded','true')) {
 output here
}
jQuery doesn't have a hasAttribute method, so I'm assuming $ = docuument.querySelector. (Note: not document.querySelectorAll; so, you're only considering a single element).
The hasAttribute method takes a single parameter: the name of the attribute you are checking for. To check that attribute's value, you'll need to use getAttribute and then compare that. So you might do:
if( $('.classname').getAttribute('aria-expanded') === 'true') {}
If you are using jQuery, then you can just use the attr method:
if ($('.classname').attr('aria-expanded') === 'true') {}
See also the MDN docs for hasAttribute.
If you're trying to check a set of elements, you could do something like this:
function allHaveAttribute(elements, attrName, attrValue) {
// First, check that all elements have the attribute
for (var i = 0; i < elements.length; i++) {
if (!elements[i].hasAttribute(attrName)) return false;
}
if (attrValue) { // if we're checking their value...
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute(attrName) !== attrValue)
return false;
}
return true;
} else { // we know all elements have the attribute
return true;
}
}
var els = document.querySelectorAll('.classname');
if (allHaveAttribute(els, 'aria-expanded', 'true') {
// action here
}
JSBin Example: http://jsbin.com/payaqijeqa/edit?js,console
jQuery doesn't have a .hasAttribute function
If it did, it would most likely only work on the first of the set
The following uses native JavaScript (ES5) to check that .every element in the set document.querySelectorAll('.classname') has that attribute set to true.
let allSet = [].every.call(document.querySelectorAll('.classname'), function(el) {
return el.getAttribute('aria-expanded') === 'true';
});
NB: the above test is case sensitive. It also ignore any elements that don't have that attribute at all. If the latter is an issue:
let allSet = [].every.call(document.querySelectorAll('.classname'), function(el) {
return el.hasAttribute('aria-expanded') && el.getAttribute('aria-expanded') === 'true';
});
You can check to see if every element with class "className" has the attribute "aria-expanded='true'" with:
if( $(".className").length === $(".className").filter("[aria-expanded='true']").length) {
//output here
}
CSS has attribute selectors that allow selection of elements with certain attributes. If you negate the selector (which is unique to jQuery), you can test if there are any elements that have the class but don't have the attribute value by using:
$(".className[aria-expanded!='true']").length == 0

Avoid jquery function for all the content

I have a table with 20 rows. In each row there is an element
<p class="exp-date">'.$cust->Expiration_Date.'</p>
This element is going to be repeated and return different values but in a lot of rows return 0001-01-01.
I want to hide this content so I wrote this in javascript
var exp = $(".exp-date").val();
var exphide = '0001-01-01';
if(exp = exphide) {
$(".exp-date").html('');
}
and also have tried this
$('.exp-date').each(function() {
if(exp = exphide) {
$(".exp-date").html('');
}
});
But in both cases apply the jquery on the first row and modify everything not only where the statement is declared.
Someone any idea?
Thanks in advance
You're using assignment in if statement. The condition exp = exphide will always evaluate to true and the code inside the if statement will execute for all the elements.
Change
if(exp = exphide) {
to
if(exp == exphide) {
or
if(exp === exphide) {
Also, use text() instead of html() to get the date, and use trim() on it to remove extra spaces before comparing.
Use this/$(this) inside the each to get the innerText of the current element.
$('.exp-date').each(function () {
if ($(this).text().trim() == exphide) {
// ^^^^^^^^^^^^^^^^^^^^^^^^
$(this).html('');
// ^^^^
}
});
Use == and "this", else it will point to all classes. Code shown below
var exphide = '0001-01-01';
$('.exp-date').each(function() {
if(this.innerHTML == exphide) { //this.innerHTML
$(this).html(''); //this.html..else will point to all classes
}
});
First you should correct the syntax in the if condition and then try the below code. When you are using "each" for looping you should pass index and value to the callback function as shown below. Then you can achieve the desired result.
var exphide = '0001-01-01';
$('.exp-date').each(function(index, value) {
var exp = $(value).text();
if(exp == exphide) {
$(value).html('');
}
});
I suggest not to remove the content from table cell instead you can hide. Hope this helps.

How to add class to a jQuery element if a condition is true and remove the same class if the condition is false?

Is there a shorter way to do the following?
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
if (is_checked) {
select_all_checkbox.parent().addClass("selected");
} else {
select_all_checkbox.parent().removeClass("selected");
}
Use toggleClass, passing a second argument (a boolean) that specifies whether the class should be added or not:
select_all_checkbox.parent().toggleClass("selected", is_checked);
If you have multiple elements selected by input.select_all, you have to iterate over them though:
$("input.select_all").each(function() {
$(this).parent().toggleClass('selected', this.checked);
});
Absolutely! You can choose between the methods (addClass/removeClass) programmatically, and use the one that is returned when an expression is executed.
Like this:
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
select_all_checkbox.parent()[is_checked ? "addClass" : "removeClass"]("selected");

Including a for loop in an if statement

I'm building an application in which I want to display some errors when a user enters invalid values in an input box. A correct value is appended as 'entry' to a div if no errors were found. In total there are 3 cases when to display errors:
The input value is empty
The input value is a number
The input value already exists
These errors are displayed with if else statements.
1.and 2. were easy, but the problem case (3.) only validates against the first element of class .cat_entry.
if(cat_input == '') { // generate errors
errorDisplay(error_input_empty);
} else if(!isNaN(cat_input)) {
errorDisplay(error_input_number);
} else if($('.cat_entry') == cat_input) { // THIS IS THE PROBLEMATIC LINE
// .cat_entry is the class of the entries that have been appended
errorDisplay(error_duplicate);
} else {
// stuff
};
So I believe I need a for loop/ .each() (no problem so far), but how do I include this as a condition in an if statement? Something like.. if( for(i=0;i<$('.cat_entry').length;i++) { ... }; ... How to return true (or something similar) when one of the entries matches the input value, then pass the return value to the if statement?
EDIT: here is a jsFiddle with the relevant code. I updated it with $.inArray() method. I'd like to try and use this instead of a for / .each() loop.
You can try this:
var a=$('.cat_entry'),o={};
for(i=0;i<a.length;i++) {
var s=a[i].val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
or
var o={};
$('.cat_entry').each(function(){
var s=$(this).val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
You can actually use the jQuery inArray function for this, such as:
else if($.inArray(cat_input, $('.cat_entry') != -1)
}
The solution was to add this to the function:
var isDuplicate = false;
$('.cat_entry').each(function() {
if(!$(this).text().indexOf(cat_input)) {
isDuplicate = true;
}
// And in the if else loop:
else if(isDuplicate == true)
//and just before the function ends
isDuplicate = false;
Thanks to all for the help you offered.

Categories