JavaScript - If checkbox is disabled, add class using jQuery - javascript

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

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"]')

JQuery not removing active class

I'm trying to make my links slide down over the page when the mobile nav is clicked and the content to disappear so only the links are shown. I have got this basically working but the .displayNone class will not remove when I click the mobilenav again and I'm a bit dumfounded as to why.
$(document).ready(function() {
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('.displayNone');
if(status){ $('.wrapper').removeClass('.displayNone'); }
else { $('.wrapper').addClass('displayNone'); }
});
});
Bit of newbie to all this. Anything obvious that anyone can see wrong with this?
Use toggleClass(),
$('.wrapper').toggleClass('displayNone');
And, jQuery's xxxClass() functions expect the name of the class, not the selector, so leave off the . class selector.
When adding/removing classes, just use displayNone, not .displayNone (note the dot!).
Also there's a toggleClass() function which saves you from doing the status thing, which means you just need to do
$('.wrapper').toggleClass('displayNone');
your are doing bit wrong
var status = $('.wrapper').hasClass('.displayNone');
when you use hasClass, addClass or removeClass then you don't need to have '.' dot before class name.
so correct way is
var status = $('.wrapper').hasClass('displayNone');
your code after correction
$(document).ready(function() {
$('#hamburger').on('click', function() {
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('displayNone');
if (status) {
$('.wrapper').removeClass('displayNone');
} else {
$('.wrapper').addClass('displayNone');
}
});
});
You can use :
$('.wrapper').toggleClass("displayNone");
Final code :
$(document).ready(function(){
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
$('.wrapper').toggleClass("displayNone");
})
})

JS with select boxes

I am currently working on a bit of javascript that will execute when a checkbox is checked.
When the checkbox is checked, the form will display 2 more select boxes.
I've attempted something but i'm not very good with javascript, can someone take a look and lemme know where i'm going wrong?
$(document).ready(function() {
$("#repeat").change(function () {
if ($("#repeat").checked){
$("#numbers").slideDown();
} else{
$("#numbers").slideUp();
}
});
$("#numbers").hide();
$("#repeat").tigger("change");
});
And the id of the checkbox is repeat and id of one of the select boxes is numbers.
This part is not correct:
$("#repeat").checked
and should be
this.checked
So whole script:
$(document).ready(function () {
$("#repeat").change(function () {
if (this.checked) {
$("#numbers").slideDown();
} else {
$("#numbers").slideUp();
}
});
$("#numbers").hide();
$("#repeat").trigger("change"); // <--- trigger, not tigger
});
$("#repeat") is a jQuery instance object, it doesn't have a property checked. However this inside of change event handler refers to the HTMLSelectElement which has this property.
Also it's trigger not tigger.

Using jQuery $(this) to select anything in this form

have multiple forms on one page but all with the same class name.
I want to make it so that if there is no content in the text area, the submit button is disabled.
This works as you can see here i have done that:
http://jsfiddle.net/WJnqw/
However, this obviously will affect all of the forms with the same submit button classname.
I have tried changing the code to include e.g:
$(this).find(".addcommentbutton").prop("disabled", true);
As i thought that would select the form, and find the add comment button.
But it doesnt work.
Any help?
Thanks!
The problem is that this was the window. You need to pass the context somehow.
Here's a working version that shows two ways of either specifying what this in the function refers to or letting jquery do it:
http://jsfiddle.net/LVf5w/
$(document).ready(function () {
$('.addpostcomment').each(function() {
disableComments.call(this); // specify what "this" will be in the function
});
$(".addpostcomment").keyup(disableComments); //let jquery specify that "this" will be the element
});
function disableComments() {
$(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);
};
You could also just do this instead of iterating and calling the function:
http://jsfiddle.net/LX2Dj/
$(document).ready(function () {
$(".addpostcomment").keyup(disableComments).trigger('keyup');
});
Or (my preference) do away with the anonymous function altogether:
http://jsfiddle.net/sfuHU/
$(document).ready(function () {
$(".addpostcomment").keyup(function() {
$(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);
}).trigger('keyup');
});
Note that you have duplicate ids on your elements. The id must be unique.
JSFIDDLE DEMO
You need to use .next() not find & also use this directly in the keyup event
$(this).next('.addcommentbutton').prop('disabled', !($(this).val().length > 0));
// comment form not allow submit when empty
$(document).ready(function () {
disableComments();
$( ".addpostcomment" ).keyup(function() {
$(this).next('.addcommentbutton').prop('disabled', !($(this).val().length > 0));
});
});
function disableComments() {
var commentLength = $('.addpostcomment').val().length;
if (commentLength < 1) {
$(".addcommentbutton").prop("disabled", true);
} else {
$(".addcommentbutton").prop("disabled", false);
}
};

Removing a class from all input elements

I want to remove a class from my input elements.I'm using Data Annotations in MVC and unobtrusive javascript for validation,anyway, when user clicks submit button I want to remove valid class from all input elements, because it change all unnecessary input's (non-required) valid (green border color) and it's not looking good.Anyway, I try this:
$("#submitBtn").click(function () {
if ($(".input-validation-error").length == 0) { // if there is no error
$(this).button('loading');
} else {
$("input").each(function () {
$(this).removeClass("valid");
});
}
And it didn't work, also tried:
$("input").removeClass("valid");
It didn't work either.And I thought maybe it's working before the validation and valid class adding after the click event automatically.So I try this:
setInterval(function() {
$("input").each(function() {
$(this).removeClass("valid");
});
}, 1000);
But still no success. I don't know jQuery very well, probably I'm missing something simple.What is the problem?
if the class is attached to the input element then it should be as simple as
$("input.valid").removeClass('valid')
As it turned out OP didn't want the valid highlight to be applied so setting the validClass to '' fixed it
For the page the default validClass was set using
jQuery.validator.setDefaults({ validClass: '' });
Try to wrap your code inside DOM ready:
$(document).ready(function() {
$("#submitBtn").click(function () {
if ($(".input-validation-error").length == 0) { // if there is no error
$(this).button('loading');
} else {
$("input").each(function () {
$(this).removeClass("valid");
});
}
})
Check out this fiddle:
http://jsfiddle.net/dwQb4/1/
$("input").removeClass("valid");
There are 3 inputs with class="valid" that turns them green and some jquery to remove the class
this may help you

Categories

Resources