Why this code doesn't hide the checkbox? - javascript

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

Related

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.

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

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/

Don't trigger JQuery on a disabled checkbox

I have a form with checkboxes. When users click on label, I have custom checkbox icon that gets swapped. That works fine, but I also have disabled checkboxes in the form, and I don't wan't the click event to be triggered when you click on the disabled ones. How do I do that?
JQuery:
$('input[type=checkbox] + label').click(function() {
$(this).toggleClass('checkbox-pressed');
});
HTML:
<input type="checkbox" id="A"><label for="A">Option 1</label>
<input disabled type="checkbox" id="B"><label for="B">Option 2 - don't trigger JQ</label>
Use :not(:disabled) to select only those checkboxes that aren't disabled.
$('input[type=checkbox]:not(:disabled)').click(function() {
...
});
Documentation: :not() and :disabled
You should rather use .on(). Otherwise it won't work for checkboxes that become disabled after the page loads up initially (say, because of some user action):
$(document).on('click', 'input[type=checkbox]:not(:disabled)', function() {
...
});
You can use the :enabled selector like this:
$(':checkbox:enabled').click(function() {
// Your code here...
});
it would be easier to use :checked in jQuery
you can find more here.

How can I prevent jquery from selecting a parent when I click on one of the children in that parent?

ok quick scenario:
html:
<span class="answer">blah<input type="radio" value="1"></span>
jquery:
$("span.answer").click(
function() {
check = $("input", this);
check.attr('checked', check.attr('checked') === true ? false : true);
);
Ok so this will check/uncheck the child radio input inside the selected span when I click inside it.
The problem I have is that I don't want to run this event when I actually click on the radio button itself (obviously because jquery will see the radio button as checked and uncheck - in effect the exact opposite of what should happen usually). Something along the lines of this:
$("span.answer:not(span input)").click
This of course doesn't work. Any ideas? Thanks in advance!
Leo
$("span.answer input").click(function(evt)
{
evt.stopPropagation();
});
Will prevent the click event from bubbling up (and triggering the handler on "span.answer".)
There is a specific html tag to accomplish what you try to do with jquery and javascript ..
it is the label tag
<label>blah<input type="radio" value="1" /></label>
this will have the effect you want
[update]
For Internet Explorer 6 to play nice use the complete syntax of the label by using the for attribute which targets the id of an form input/select/etc.. element..
<label for="radio_1">blah<input id="radio_1" type="radio" value="1" /></label>

Categories

Resources