Toggle disable/enable checkbox by replacing class name - javascript

I have a set of 5 checkboxes with class set to "child". I want that if I select one checkbox, rest of them goes disabled. I have tried following code but it disables the all checkboxes.
if ( !$(this).is ( ":checked" ) ) {
$(this).removeClass().addClass("hand .parent");
$(".child").attr ( "disabled" , true );
}
then even i tried adding this
$(this).removeAttr ( "disabled" );
but it still disables the all controls
help plz! Thanks

Are you trying to do something like this?
See it here: http://jsfiddle.net/fEA3Y/
var $cbox = $('.child').change(function() {
if(this.checked) {
$cbox.not(this).attr('disabled','disabled');
} else {
$cbox.removeAttr('disabled');
}
});​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
If you really need to toggle classes for some reason, you could do this:
http://jsfiddle.net/fEA3Y/2/
var $cbox = $('.child').change(function() {
if(this.checked) {
$(this).toggleClass('child parent');
$cbox.not(this).attr('disabled','disabled');
} else {
$(this).toggleClass('child parent');
$cbox.removeAttr('disabled');
}
});​

Did you do
$('.child').removeAttr('disabled')
Since you tried it on .child, it's kind of hard to tell the context of this since you're not posting the full code.
Also, are you there there isn't a readonly attribute being set somewhere?

Related

JS overides check in the checkbox on toggle [duplicate]

I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:
$('input#myId').toggle(
function(){
//do stuff
},
function(){
//do other stuff
}
);
The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)
I've tried the following:
$('input#myId').attr('checked', 'checked');
and
$(this).attr('checked', 'checked');
and even simply
return true;
But nothing is working. Can anyone tell me where I'm going wrong?
Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)
$('input#myInput').change(function ()
{
if(!$(this).hasClass("checked"))
{
//do stuff if the checkbox isn't checked
$(this).addClass("checked");
return;
}
//do stuff if the checkbox isn't checked
$(this).removeClass('checked');
});
Thanks again to all who replied.
Use the change event instead of the toggle event, like such:
$('input#myId').change(function () {
if ($(this).attr("checked")) {
//do the stuff that you would do when 'checked'
return;
}
//Here do the stuff you want to do when 'unchecked'
});
While using the change event handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the change event until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksMode say, "it's a serious bug".
You might want to use the click event handler, but that won't work with keyboard navigation. You need to register a keyup handler too...
See also this related question.
I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).
Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checked class, you may use HTML's checked attribute:
$('input#myInput').change(function () {
if ($(this).attr("checked")) {
//do stuff if the checkbox is checked
} else {
//do stuff if the checkbox isn't checked
}
});
Any browser sets the checked attribute of an input element to the value "checked" if the checkbox is checked, and sets it to null (or deletes the attribute) if the checkbox is not checked.
why not using $.is() ?
$('input#myId').change(
function() {
if ($(this).is(':checked')) {
// do stuff here
} else {
// do other stuff here
}
});
This is an answer by MorningZ (I found it here) that makes totally sense:
The part you are missing is that "checkbox" is a jQuery object, not a
checkbox DOM object
so:
checkbox.checked sure would error because there is no .checked property of a jQuery
object
so:
checkbox[0].checked would work since the first item on a jQuery array is the DOM object
itself.
So in your change() function you can use
$(this)[0].checked
$('input#myId').toggle(
function(e){
e.preventDefault();
//do stuff
$(this).attr('checked', 'true');
},
function(e){
e.preventDefault();
//do other stuff
$(this).attr('checked', 'false');
}
);
this worked for me............ check it
$(":checkbox").click(function(){
if($(this).attr("id").split("chk_all")[1])
{
var ty = "sel"+$(this).attr("id").split("chk_all")[1]+"[]";
if($(this).attr("checked"))
{
$('input[name="'+ty+'"]').attr("checked", "checked");
}
else
{
$('input[name="'+ty+'"]').removeAttr("checked");
}
}
})
I did a similar approach but simply using the checked attribute such as
//toggles checkbox on/off
$("input:checkbox").change(
function(){
if(!this.checked){
this.checked=true;
}
else{
this.checked=false;
}
}
);
//end toggle
$("input[type=checkbox][checked=false]")// be shure to set to false on ready
$("input#Checkbox1").change(function() {
if ($(this).attr("checked")) {
$("#chk1").html("you just selected me")//the lable
} else {$("#chk1").html("you just un selected me") }
});
Try using a non-jquery function:
function chkboxToggle() {
if ($('input#chkbox').attr('checked'))
// do something
else
// do something else
}
then in your form:
<input id="chkbox" type="checkbox" onclick="chkboxToggle()" />
Try:
$(":checkbox").click(function(){
if($(this).attr("checked"))
{
$('input[name="name[]"]').attr("checked", "checked");
}
else
{
$('input[name="name[]"]').removeAttr("checked");
}
})

Toggle Show and Enable Textfiled When Certain Radio Button is Selected

I would like to be able to have an input field (initially hidden and disabled) to be shown and enabled every time the "Other" radio button is selected, and ofcoure to be hidden and disabled when a different radio button is selected . I have gotten this script to show and hide the textfield appropriately, but Id like to know how I can get enabling and disabling to happen with it
$('input[name="x_description"]').bind('change',function(){
var showOrHide = ($(this).val() == "Other") ? true : false;
$('#other_program_text').toggle(showOrHide);
});
I know that this is how to show the field and enable the textfield, but cant figure out how to put it all together,
$(this).show().prop('disabled', false);
Thanks in advance,
Dan
$('input[name="x_description"]').bind('change',function(){
if ( showOrHide == true ) {
$('#other_program_text').show().prop('disabled',false);
} else if ( showOrHide == false ) {
$('#other_program_text').hide().prop('disabled',true);
}
});
You want to use the $(this).attr() function to set properties on an HTML element. With one parameter it'll read the passed param, with two it'll set it.
Like $(this).attr("enabled", true)
You can use "click" method
$('input[name="x_description"]').click(function() {
if($('#radio_button').is(':checked')) {
alert("it's checked"); //do your stuff
}
});
If your content are dynamically generated then use "live" method
$('input[name="x_description"]').live('click',function() {
if($('#radio_button').is(':checked')) {
alert("it's checked"); //do your stuff
}
});

More efficient javascript boolean

I have a checkbox and some <div>s that show/hides whenever a checkbox is checked. Now it all works great but it could be more efficient.
jQuery("#filtertype").change(function () {
if (jQuery("#posttype").is(":checked")) {
jQuery("#postblock").slideDown("slow");
} else {
jQuery("#postblock").slideUp("slow");
}
if (jQuery("#taxonomycat").is(":checked")) {
jQuery("#taxonomyblock").slideDown("slow");
} else {
jQuery("#taxonomyblock").slideUp("slow");
}
if (jQuery("#taxonomytag").is(":checked")) {
jQuery("#taxonomyblocktag").slideDown("slow");
} else {
jQuery("#taxonomyblocktag").slideUp("slow");
}
if (jQuery("#fieldjeskey").is(":checked")) {
jQuery("#fieldblock").slideDown("slow");
} else {
jQuery("#fieldblock").slideUp("slow");
}
if (jQuery("#sliderme").is(":checked")) {
jQuery("#sliderblock").slideDown("slow");
} else {
jQuery("#sliderblock").slideUp("slow");
}
});
This works like it should; it gets the ID of the checkbox <input> and for every <input> (#filtertype, #taxonomycat etc.) it will show or hide a <div> (#postblock, #taxonomyblock etc.)
It may be smarter to get the ID of every <input> and toggle the slideUp, slideDown function.
How can this be done?
Firstly, rather than have a list of id selectors, put a single class of each of those checkboxes, along with a data attribute to specify the relation. Something like this:
<input type="checkbox" name="posttype" class="filter-checkbox" data-rel="postblock" value="foobar" />
Then in javascript you can simplify all the code above to the following:
jQuery("#filtertype").change(function() {
$('.filter-checkbox').each(function() {
var func = this.checked ? 'slideDown' : 'slideUp';
$('#' + $(this).data('rel'))[func]('slow');
});
});
Example fiddle
It could be more efficient by not using jQuery.
Replace all of your jQuery("#someID").is(":checked") with
document.getElementById('someID').checked, and short of writing your own lightweight animation engine that's as good as you'll get.
Or you can go down the dark path of obscurity:
jQuery("#postblock")["slide"+(document.getElementById('posttype').checked ? "Down" : "Up")]("slow");
But that's probably not a good idea :p

Change background image width with checkbox?

I have simple Chrome extension that injects some html into a game webpage that lets a user customize the background image of the webpage. It stores the URL of the image with setlocalstorage so that when they return to the game the custom background image is still there. I've included some CSS that forces the image to fit the width of the browser window. This satisfies most users but, there are a few that have requested I allow them to turn off the width-matching feature. What I'd like to do is add a check box to allow the user to turn off the width adjustment.
I'm thinking some sort of "if the box is checked apply this class to the body tag" sort of thing but, I can't seem to figure it out.
If someone could show me how to accomplish this I'd really appreciate it!
Attach an onchange event listener to the checkbox that checks the value of 'checked' for your checkbox element and adds/removes the class:
yourCheckboxElement.addEventListener('change', function(e){
document.body.classList[this.checked ? "add" : "remove"]("someClass");
/* save value of this.checked to localStorage here */
});
jsFiddle example: http://jsfiddle.net/8RC2m/1/
Change css when checkbox is marked:
$("#new").click(function() {
if (this.checked){
$(this).closest('p').addClass('white');
} else {
$(this).closest('p').removeClass('white');
}
});
add styles:
.white {
color: white;
}
That might work for you, no?
Additionally,
$(":checkbox").attr("autocomplete", "on");
Wrap your width adjustment code in a css class like width-adjustment. Then try something like this:
if ($('#IdOfYourCheckBox').is(":checked") == true){
$("#ElementToChange").removeClass('width-adjustment');
}
You have requested JavaScript only so i will avoid jQuery, try something like this:
var b = document.getElementsByTagName("body")[0];
if (document.getElementById('checkbox-id').checked){
b.className +=" yourclass";
}
hope it helps
You can use this script to check if the chkbox is checked or not.
(function( $ ){
$.fn.check = function( handler ) {
if (handler) {
this.each(function() {
$(this).change(function() {
if ($(this).attr('checked')) {
handler.call(this);
$(this).closest('p').addClass('white');
}
});
});
} else {
this.each(function() {
$(this).attr('checked', true);
$(this).change();
$(this).closest('p').addClass('white');
});
}
};
$.fn.uncheck = function( handler ) {
if (handler) {
this.each(function() {
$(this).change(function() {
if (!$(this).attr('checked')) {
handler.call(this);
$(this).closest('p').removeClass('white');
}
});
});
} else {
this.each(function() {
$(this).attr('checked', false);
$(this).change();
$(this).closest('p').removeClass('white');
});
}
};
})( jQuery );

jQuery won't set SELECTED

I have an annoying problem where I have a jQuery selecting the various options of a SELECT option list. I want to set the SELECTED=SELECTED attribute to force something other than the first item to be the default.
Seems pretty basic, and if I set other characteristics of the OPTION tag it works fine. For instance:
$(this).addClass ('TEST');
works as you'd expect by adding the TEST class to what should be the default option. I also can do the following:
$(this).attr('annoying', "SELECTED");
This adds the attribute "annoying" with the value of "SELECTED. Sadly if I do the following:
$(this).attr('SELECTED', "SELECTED");
it just completely ignores it. If I go into Chrome's debugger and punch this in manually it does work but not from my JS file. :^(
Any ideas?
UPDATE
Great suggestions so far but as nothings working I suspect something else is amiss. To provide further context ... this is a Wordpress site and I'm making the QuickEdit function bring up the right OPTION in a custom attribute to a taxonomy. For those of you who don't know Wordpress its probably not important (who knows at this stage).
Here's the full code:
jQuery(document).ready(
function ($) {
$('.editinline').on ('click',
function () {
var $data_ref = $(this).closest('tr');
$('.bespoke-item.quick-edit').each (
function () {
var col_name = $(this).attr('name');
var col_value = $data_ref.find ('.' + col_name).text();
$(this).val(col_value); // this will work for non-enumerated widgets
if ( $(this).is( "select" ) ) {
selected = false; // used as a flag on whether the SELECTED value has been found
options = $(this).find ('.select-option');
options.each(
function () {
if ( $(this).attr('value') == col_value ) {
$(this).addClass ('TEST');
selected = true;
$(this).attr('SELECTED', "SELECTED");
this.selected = 'SELECTED';
}
}
);
if ( !selected ) {
// The value of the did not match any of the selections (this likely means it wasn't set at all)
// In this case revert to the "static-default" setting
options.each(
function () {
if ( $(this).attr('static-default') ) {
$(this).attr ('SELECTED' , 'SELECTED');
alert ("Found value in static default " + $(this).val());
selected = true;
} else {
$(this).removeAttr ( 'SELECTED' );
}
}
);
}
}
}
);
}
);
});
Three options for you (all assume that this is the option element in question, as it seems to be in your question):
If you're using a recent copy of jQuery, it could be the attr vs. prop thing (also note that selected should be in lower case, not caps):
$(this).prop('selected', true);
Sometimes it's simpler just to use the DOM directly:
this.selected = true;
Or, of course, use val on the select element, setting it to the value of the option you want selected.
$("selector for the select element").val($(this).val());
// or better (as `value` is entirely reliable on option elements):
$("selector for the select element").val(this.value);
Live Examples of All Three | Source

Categories