Unable to enable/disable checkbox via [selector].attr & .removeattr - javascript

Fiddle:
http://jsfiddle.net/KU29Q/1/
Goal is to be able to enable and disable a checkbox dynamically. I've tried by referencing the class and/OR id of the checkboxes in question and then use .attr("disabled", "disabled") or .removeAttr("disabled")
<input id="check" type="checkbox" disabled="disabled" class="enableDisable"><label for="check2" >Initially Disabled</label>
<input id="check2" type="checkbox" class="enableDisable"><label for="check2" >Initially Enabled</label>
//attempt to ENABLE checkbox1
$("check").removeAttr('disabled');
//attempt to change state of second checkbox - DISABLE it...
$(".enableDisable").attr("disabled","disabled");
$("#check2").attr("disabled", "disabled");
Also have tried playing around with [selector].prop to no avail. Can someone give me a push in the right direction and/or punch me in the face to relieve my agita?
Thanks.

JSFIDDLE DEMO
Use .prop() instead of .attr()
For targeting ids use # (hash)
For classes use . (dot)
//attempt to ENABLE checkbox1
$("#check").prop('disabled', false);
//attempt to change state of second checkbox - DISABLE it...
$("#check2").prop("disabled",true);

1. You need to include jQuery in your fiddle
2. Your class applies to both elements, so when you use it as a selector for disabling, you disable both elements:
$(".enableDisable").attr("disabled","disabled");
You should just use the (unique) IDs instead and remove the class selector line:
$("#check").removeAttr('disabled');
$('#check2').attr('disabled', 'disabled');
Your updated fiddle: http://jsfiddle.net/KU29Q/2/

Related

Disable one group of select elements with checkbox using javascript / jquery

I have a one or more groups of select elements. I need to disable one at a time but both are being disabled. I am using a checkbox to activate the disable action. I am using javascript / jquery.
$(document).ready(function(){
$('#hour-check').change(function() {
$('select').prop('disabled', this.checked);
});
});
JSFiddle LINK
You're using the same id for each check box. These should be unique, or preferably, use a class.
You should also wrap the tables in a containing class to make traversing the DOM easier.
<div class="table-container">
<p>
<input type='checkbox' class="hour-check"> 24hr
</p>
...
Once you've done this you can use the following to disable the appropriate selects:
$('.hour-check').change(function() {
$(this).parents('.table-container').find('select').prop('disabled', this.checked)
});
See https://jsfiddle.net/d58euhas/

iCheck and manual setting of checkbox to checked

I'm using the iCheck framework and I have two inputs
<input name="group" id="id1" type="radio" checked>
<input name="group" id="id2" type="radio">
<input name="group" id="id3" type="radio">
<input name="group" id="id4" type="radio">
On click I call an ajax function. If something fail, I want to set back the checked attribute to the previously selected input.
var currentChecked = $("input[name='group']:radio:checked");
$("input[name='group']:radio").each(function() {
$(this).on('ifChecked', function(){
$.ajax({
url: "/ajax/something/"
})
.done(function (data) {
currentChecked = $(this);
})
.fail(function (data) {
$(this).removeAttr('checked');
currentChecked.prop('checked', true);
});
});
});
But this will not reset the checked checkbox. There is something I don't see from the iCheck framework? Any solution?
Actually in case of iCheck You need to update the iCheck to reflect the changes on Jquery.
You can update using iCheck('update')
$(this).iCheck('update');
After checked or unchecked the radio button using jquery.
Another Solution just check or uncheck the iCheck using his predefined function.
<input name="group" id="id1" type="radio" checked>
If the above one is your radio button you can use the code in jquery section like below
$('#id1').iCheck('uncheck'); //To uncheck the radio button
$('#id1').iCheck('check'); //To check the radio button
In this case no need to use the iCheck('update')
jQuery iCheck works bit different from the way you expect.
When you initialize a checkbox or radio button, it picks up the status/value of the control and builds the look and feel of that state. That is all. Then it never checks your control value or any update to its attributes.
So the only way to uncheck your checkbox in the Ajax failure event, is by using the functions exposed by the plugin.
You should use following in your ajax fail event to change the state back to previous
$(this).iCheck('toggle');
or you can change the html attributes and refresh the control like below
$(this).removeAttr('checked');
currentChecked.prop('checked', true);
$(this).iCheck('update'); — apply input changes, which were done outside the plugin
Below solution worked for me in iCheck v1.0.2.
You can check iCheck radio by filtering radio button group like below
Using 'id' of element
$('input:radio[name="group"]').filter('[id="id1"]').iCheck('check');
Using 'value'
$('input:radio[name="group"]').filter('[value="id1"]').iCheck('check');
you can replace 'id' or 'value' dynamically base on your requirement/functionality.
and you can change 'check' or 'uncheck' inside .iCheck('check').
//this will update all iCheck fields inside the selected form
$('#form_id :radio').iCheck('update');

Bootstrap: how to check if an elment is checked and set it to disable if checked

This code works great but is missing something I need.
Basically if the input has a checked="checked" attribute, it should keep the other two elements disabled. if it is not checked the elements are enabled.
Here's my code on jsFiddle: http://jsfiddle.net/arunpjohny/gMgm7/1/
And this would be my input
<input class="test_priv1" type="checkbox" name="custom" id="custom" checked="checked" onclick="" />
I guess this would be translated to:
If my input gets a check, disable the other two elements. If my input has the checked="checked" then keep my other two elements disabled. If my input is unchecked enable the two elements.
Got it working:
$(document).ready(function() {
if ($('.test_priv1').is(':checked')){
$('.test_priv2, .test_priv3').prop('disabled',true);
}
$('.test_priv1').change(function () {
if(this.checked){
$('.test_priv2, .test_priv3').prop('disabled',true);
}else{
$('.test_priv2, .test_priv3').removeAttr('disabled');
}
});
});
Here's a demo
#Dan had it right with checking on ready, but for some reason running .checked off the element does not seem to work. However, if you use $('.test_priv1').is(':checked') then it seems to work properly. See this fiddle for an example of it working on both page load and on change.

Why this code doesn't hide the checkbox?

I want to show some input checkbox inside a form only if a certain other checkbox is checked.
I´ve read about .show() and .hide() but I want to do it changing the css selector.
My problem is that the hidden selector isn't hidden at all: It is printed out without any regard of the checkbox.
Please note that this is just a test, I'm learning jQuery and wanted to try it out.
This is what I've tried (JSfiddle)
HTML FORM:
<form name="ejemplo">
<input type="checkbox" name="checkbox1" id="idCheckbox1" value="check" checked>Sí?
<input type="checkbox" name="checkbox2" id="idCheckbox2" value="check">No
<div id="ocultar">
<input type="checkbox" name="checkbox3" id="idCheckbox3" value="check">Tal Vez</div>
</form>
JS
//Usamos jQuery para mostrar un elemento condicionalmente
if ( $("input:checkbox[id=idCheckbox2]:checked") )
$("#ocultar").css("display","inline");
else
$("#ocultar").css("display","none");
Since id is unique you can use
$("#idCheckbox2")
instead of
$("input:checkbox[id=idCheckbox2]")
To check if the checkbox is checked, you can use .is():
if($("#idCheckbox2").is(":checked"))
$("#ocultar").css("display","inline");
else
$("#ocultar").css("display","none");
You also need to use .change() event to keep track when your checkbox has been changed and shorten your code using ternary operator:
$('#idCheckbox2').change(function () {
$("#ocultar").css("display", this.checked ? 'inline' : "none");
}).change();
The .change() at the end is used to trigger the change() event on page load and execute the code if your checkbox has been checked by default.
Fiddle Demo
You need to use a change event handler so that the display properties will up updated based on checking/unchecking of the checkbox
$('#idCheckbox2').change(function(){
$("#ocultar").css("display", this.checked ? 'inline':"none");
}).change();//used to set the initial state based on checkbox value
Demo: Fiddle
You can even use .toggle() to simplify the code like in this fiddle

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Categories

Resources