Can I write this JQuery statement cleaner? - javascript

So I have the following:
var box = $(".MyCheckBox");
if (box[0].checked)
{
// Do something
}
else
{
// Do something else
}
Is there a better way of doing this using filters or something?
I know I can go:
$(".MyCheckBox")
.filter(function(index) {
return this.checked;
})
.each(function() {
// do something
});
But I need to do something in the else statement... easier way of doing this? Thanks!

You can use the built-in :checked selector:
$(".MyCheckBox:checked").each(function() {
//Do something with checked ones..
});
$(".MyCheckBox:not(:checked)").each(function() {
//Do something with unchecked ones..
});
Or filter in the each similar to what you have:
$(".MyCheckBox").each(function() {
if($(this).is(":checked")) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
Or if say you wanted to toggle a class, then use a different approach, this would give the active class to the checked ones:
$(".MyCheckBox").each(function() {
$(this).toggleClass("active", $(this).is(":checked"));
});
Update
Based on comments if you want just raw speed:
$(".MyCheckBox").each(function() {
if(this.checked) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});

attr('checked') returns the checked value of the first element anyway, so no [0] malarky.
if ($(".MyCheckBox").attr('checked')) {
// Do something
} else {
// else
}

I'd go with Nick's updated answer above, but would like to suggest that you complete your selector. i.e.,
$('input.myCheckBox').each(function(){
// tralalala...
}
... just for the fact that it makes your initial jQuery selection a bit faster. I mean, since we're debating about speed and all. ^_^

Related

How change the css with the checkbox with different names?

Currently, I have multiple checkbox inputs with different names(checkit, checktype, checklog) assigned to the inputs.
What I want to do is to have each checkbox to change the color of the background when checked.
However, I dont know how I can assign each one of the checkbox to do some tasks without duplicating the following code ?If possible some examples or tips will be great! I would love to hear from you .
Should I remove name="checkit" if I want to make all the inputs do the same thing? What if I want them to do some slightly different things?
$('input[name="checkit"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Add the following by , or give some class name to it
$('input[name="checkit"], input[name="checktype"], input[name="checklog"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Don't use the name atrribute in jQuery and add a common class to each checkbox for a common functionality and access it with class selector in jQuery as shown below.
If you want to do something different with different checkboxes apart from this, then you can add more jQuery code for that specific input tag. It will not affect this code.
$('input.someClass').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
You can remove the name part from the selector and add selector for input[type='radio']. And if you want to add a bit different logic (I think you mean different classes), you can get the name of the current checked checkbox and use it to make your logic. Something like this
$('input[type="radio"]').change(function () {
var checkboxName = $(this).prop('name');
// if(checkboxName === .....)
});
Updated according to the comment
$('input[name="checkit"], input[name="checktype"], input[name="checklog"]').change(function () {
var checkboxName = $(this).prop('name');
// .............
});
$('input[type="checkbox"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Use
$('input[type="checkbox"]')
instead of
$('input[name="checkit"]')

JavaScript - If checkbox is disabled, add class using jQuery

I'm having a problem with the syntax (or maybe with the selectors) on my code. See the demo.
I tried the following code but the results does nothing.
#1. hasAttribute():
if ($('input[type=checkbox]').hasAttribute("disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#2. is():
if ($('input[type=checkbox]').is("[disabled]")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
// ------------------------------------------------
if ($('input[type=checkbox]').is(":disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#3. prop():
if ($('input[type=checkbox]').prop("disabled", true)) {
$(this).closest('.chkbox').addClass("is-disabled");
}
So then I think the problem is on the line:
$(this).closest('.chkbox').addClass("is-disabled");
Any idea?
Thanks.
You can use :disabled selector
see here
You're using $(this) without declaring anything. Thats the reason it's not working. It works in the second example because of the .change() function gives the context of the 'thing' (this) that is changing.
This code should work as you desire.
$(function() {
// Grab all inputs with the type checkbox.
var input = $('input[type=checkbox]')
// Check for each of the input fields (i, el stands for index, element)
input.each(function(i, el) {
// Does it have the attribute disabled?
if(el.hasAttribute('disabled')) {
// Add the class 'is-disabled'
$(el).closest('.chkbox').addClass('is-disabled')
}
})
$('input[type=checkbox]').change(function(){
if ($(this).is(":checked")) {
$(this).closest('.chkbox').addClass("is-checked");
} else {
$(this).closest('.chkbox').removeClass("is-checked");
}
});
});

jquery if else statement

What am I doing wrong here? This is on jquery-mobile.
$('.ui-checkbox').click(function() {
if (
$('.ui-checkbox label.ui-checkbox-off').removeClass('off').addClass('on')) {
}else {
$('.ui-checkbox label.ui-checkbox-on').removeClass('on').addClass('off');
}
});
The first portion works, but not when I click a 2nd time.
From your comment, you seem to want
$('.ui-checkbox').click(function() {
$('label.ui-checkbox-on,label.ui-checkbox-off', this)
.toggleClass('on').toggleClass('off');
});
But this is a little strange. You could use a simple class (on) and simply do
$('.ui-checkbox').click(function() {
$('label', this).toggleClass('on');
});
You probably don't need 2 classes as usually "off" means "not on".

Selecting and deselecting multiple checkboxes

I have this:
$('input.people').attr('checked', function() {
return $.inArray(this.name, ['danB', 'lindaC']) != -1;
});
It is for a list of contacts. I want to be able to have the user click a checkbox that will select the people in a specific role and uncheck everyone else. That works. Now I want to modify this so that if someone unclicks the same checkbox that it deselects those people (and only those people). Would that be an onBlur event?
I'm thinking something like this:
$('input.people').attr('checked', function(){
return $.inArray(this.name, ['danB', 'lindaC']) != 1;
});
or would it be:
$('input.people').attr('checked', function(){
return $.inArray(this.name, ['danB', 'lindaC']) = -1;
});
And how would I integrate this with the top function? A shout out, btw, to Nick Craver for his help to date.
$('input.people').change(function ()
{
if(!$(this).hasClass("checked"))
{
//do stuff if the checkbox is checked
$(this).addClass("checked");
return;
}
//do stuff if the checkbox isn't checked
$(this).removeClass('checked');
});

Does something like jQuery.toggle(boolean) exist?

I write something similar to the following code a lot. It basically toggles an element based on some condition.
In the following made-up example, the condition is "If the agree checkbox is checked and the name field isn't empty".
$("button").click(function() {
if ($("#agree").is(":checked") && $("#name").val() != "" ) {
$("#mydiv").show();
} else {
$("#mydiv").hide();
}
});
I wish there was some sort of jQuery function that would work like this.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ish way?
Ok, so I am an idiot and need to RTM before I ask questions.
jQuery.toggle() allows you to do this out of the box.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
First, lets see if I understand what you want to do correctly...
You want to look at the state of a checkbox(checked or not) and hide or show a second div based on the status of that value.
Define this style:
.noDisplay {
display:none;
}
Use this JavaScript:
$("button").click(function() {
$("#mydiv").toggleClass("noDisplay", $("#name").val() == "");
});
The documentation from jQuery on it can be found here:
http://api.jquery.com/toggleClass/
You could write the function yourself.
function toggleIf(element, condition) {
if (condition) { element.show(); }
else { element.hide(); }
}
Then use it like this:
toggleIf($("button"), $("#agree").is(":checked") && $("#name").val() != "");
Syntax 4
$(selector).toggle(display)
display
true - to show the element.
false - to hide the element.
If toggle() is not good for you (e.g. because it animates), you can write a small jQuery plugin, like this:
$.fn.toggleIf = function(showOrHide) {
return this.each(function() {
if (showOrHide) {
return $(this).show();
} else {
return $(this).hide();
}
});
};
and then use it like this:
$(element).toggleIf(condition);

Categories

Resources