How to check if input check or not with jquery - javascript

I have this switcher (Checked):
<div class="switch try">
<label><input checked="" type="checkbox" class="checkit"><span class="lever switch-col-green"></span></label>
</div>
How to know if this one is checked or unchecked when a user click on it ?
Here what i tried:
$(document).on('click','.try',function(e){
if($(".checkit").is(':checked')) {
alert("checked");
} else {
alert("Not checked");
}
});
But i don't get it working !

Try to use this:
$(".checkit:checked").length > 0;
or
$(".checkit").is(":checked")

You need to change your html from checked="" -> checked
<input checked type="checkbox" class="checkit">
Jquery is correct as is

Related

jQuery: change visual output of checkbox to checked

When I loop over all checkboxes with class .category attached and try to change the visual output of the checkbox to checked, nothing happens. Variable 'state' returns true or false and is used to change the element it's current visual output. At this very moment nothing happens and I don't know why.
HTML:
<input type="checkbox" class="category">checky 1</span>
<input type="checkbox" class="category">checky 2</span>
<input type="checkbox" class="category">checky 3</span>
JS:
$('body').on('click','.category',click);
function click(){
$('.category').each(function(i,element){
var state = $(element).prop('checked');
$(element).prop('checked', state);
});
return false;
}
Thanks in advance.
Note that nothing happens because you're using return false in event handler. That will prevent (un)checking the checkbox.
If you're trying to implement Select All option, just do:
$(".category:first").on("click", function() {
$(".category").prop("checked", this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" class="category"/> Select all</label><br>
<label><input type="checkbox" class="category"/></label><br>
<label><input type="checkbox" class="category"/></label><br>
<label><input type="checkbox" class="category"/></label><br>
<label><input type="checkbox" class="category"/></label><br>
<label><input type="checkbox" class="category"/></label><br>
<label><input type="checkbox" class="category"/></label><br>
Try this to set your checkboxes checked.
$('body').on('click','.category',click);
function click(){
$('.category').each(function(i,element){
element.value='checked';
});
return false;
}
Try this code:
$('body').on('click','.category',click);
function click(){
$('.category').each(function(i,element){
var state = $(element).prop('checked');
$(element).prop('checked', state ? '' : 'checked');
});
return false;
}
If you perform a test over your code, you will see that the way you are trying to grab the elements is not correct. Class "category" does not exist. What you have is "category-desktop". SO if you test like this:
alert($( 'input' ).hasClass( "category" ));//False
alert($( 'input' ).hasClass( "category-desktop" ));//True
I think you are trying to do this:
$('body .category-desktop').on('click',function(){
alert("click ok");
//run your function
});
See fiddle http://jsfiddle.net/yruhL69v/4/
But to finish the code I need to understand if you want to click over any check box, or over any place on the body,or any element that has category-desktop indise body .

disable checkbox if input value is zero

i have a list of check-boxes which is created dynamically and there is input field for each check box so i want to disable the check box if input field value is zero. below is my code
HTML code
<input class="check" id="check" name="check" type="checkbox"><label for="check">checkbox <input type="hidden" id="test" value="0" /></label>
<input class="check" id="check1" name="check1" type="checkbox"><label for="check1">checkbox1 <input type="hidden" id="test" value="6" /></label>
Jquery
if($("#test").val() == "0"){
$('.check').attr("disabled", "disabled");
}
jsfiddle
You used twice id=test and JavaScript works with only the first of them.
Change id=test to class=test, or works with two differents ids.
Working code:
$('.test').each(function() {
if ($(this).val() == '0') {
$(this).parent().prev().attr('disabled', 'disabled');
}
});
http://jsfiddle.net/cDD5L/
$("input[type=hidden]").each(function() {
if($(this).val()==0){
$(this).parent().prev().attr('disabled', 'disabled');
}
});
Demo:
http://jsfiddle.net/SxypS/
Please use
$(function() {
enable_cb();
$("#group1").click(enable_cb);
});
function enable_cb() {
if (this.checked) {
$("input.group1").removeAttr("disabled");
} else {
$("input.group1").attr("disabled", true);
}
}
It will work for you.
Let me know if still not work

changing the checked attribute of checkbox using jquery

I have to control the checked status a list of checkboxes from another checkbox.
HTML:
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
<input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
<input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>
JS:
$('#readall').click(function()
{
var checkStatus = $(this).is(':checked');
var checkboxList = $('#permGrid input[rel="read"]');
$(checkboxList).attr('rel', 'read').each(function(index)
{
if(checkStatus == true)
{
$(this).attr('checked', 'checked');
console.log($(this).attr('checked'));
}
else
{
$(this).removeAttr('checked').reload();
console.log($(this).attr('checked'));
}
});
});
The above code seems fine but the check/uncheck works only for the first time. But when I click the main checkbox second time, it doesn't change the status of other checkboxes into 'checked'. Is there anything I need to do?
I found something similar here. I compared the code and mine and this code is somewhat similar but mine doesn't work.
Try using prop, and shorten the code alot like this
$('#readall').click(function () {
var checkboxList = $('#permGrid input[rel="read"]')
checkboxList.prop('checked', this.checked);
});
DEMO
You can't use a method .reload like this
$(this).removeAttr('checked').reload();
// returns Uncaught TypeError: Object #<Object> has no method 'reload'
Remove it, and it will work.
JSFiddle
Use a class for all the checkboxes which you need to change on click of some checkbox. Like:
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
I have added a class="toChange" to all the checkboxes except the first one.
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
<input id="group.read" class="toChange" name="group.read" type="checkbox" value="1" rel="read" />
<input id="ingredients.read" class="toChange" name="ingredients.read" type="checkbox" value="1" rel="read" />
</div>
Then use the following script:
$('#readall').click(function(){
var checkStatus = $(this).is(':checked');
if(checkStatus){
$(".toChange").attr('checked', 'checked');
}
else{
$(".toChange").removeAttr('checked')
}
});
Demo

Check all other checkboxes when one is checked

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):
<div id="ScrollCB">
<input type="checkbox" name="ALL" value="checked" checked="checked">
All (if nothing selected, this is default) <br>
<c:forEach items="${serviceList}" var="service">
<input type="checkbox" name="${service}" value="checked"> ${service} <br>
</c:forEach>
</div>
What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).
I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):
<script type="text/javascript">
$ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
$(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>
Could you tell me some simple approach how to get it work? Thanks a lot!
demo
updated_demo
HTML:
<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
JS:
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('div input').attr('checked', true);
} else {
$('div input').attr('checked', false);
}
});
HTML:
<form>
<label>
<input type="checkbox" id="selectall"/> Select all
</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
</form>
JS:
$('#selectall').click(function() {
$(this.form.elements).filter(':checkbox').prop('checked', this.checked);
});
http://jsfiddle.net/wDnAd/1/
Thanks to #Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.
FIDDLE
HTML
<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>
SCRIPT
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('input:checkbox').prop('checked', true);
} else {
$('input:checkbox').prop('checked', false);
}
});
And now add this to manage the master checkbox as well...
$("input[type='checkbox'].justone").change(function(){
var a = $("input[type='checkbox'].justone");
if(a.length == a.filter(":checked").length){
$('.selectall').prop('checked', true);
}
else {
$('.selectall').prop('checked', false);
}
});
Add extra script according to your checkbox group:
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('colors[]');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
HTML Code:
<input type="checkbox" id="selectall" onClick="selectAll(this,'color')" />Select All
<ul>
<li><input type="checkbox" name="colors[]" value="red" />Red</li>
<li><input type="checkbox" name="colors[]" value="blue" />Blue</li>
<li><input type="checkbox" name="colors[]" value="green" />Green</li>
<li><input type="checkbox" name="colors[]" value="black" />Black</li>
</ul>
use this i hope to help you i know that this is a late answer but if any one come here again
$("#all").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Only in JavaScript with auto check/uncheck functionality of master when any child is checked/unchecked.
function FnCheckAll()
{
var ChildChkBoxes = document.getElementsByName("ChildCheckBox");
for (i = 0; i < ChildChkBoxes.length; i++)
{
ChildChkBoxes[i].checked = document.forms[0].CheckAll.checked;
}
}
function FnCheckChild()
{
if (document.forms[0].ChildCheckBox.length > document.querySelectorAll('input[name="ChildCheckBox"]:checked').length)
document.forms[0].CheckAll.checked = false;
else
document.forms[0].CheckAll.checked = true;
}
Master CheckBox:
<input type="checkbox" name="CheckAll" id="CheckAll" onchange="FnCheckAll()" />
Child CheckBox:
<input type="checkbox" name="ChildCheckBox" id="ChildCheckBox" onchange="FnCheckChild()" value="#employee.Id" />```
You can use jQuery like so:
jQuery
$('[name="ALL"]:checkbox').change(function () {
if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
else $('input:checkbox').removeAttr('checked');
});
A fiddle.
var selectedIds = [];
function toggle(source) {
checkboxes = document.getElementsByName('ALL');
for ( var i in checkboxes)
checkboxes[i].checked = source.checked;
}
function addSelects() {
var ids = document.getElementsByName('ALL');
for ( var i = 0; i < ids.length; i++) {
if (ids[i].checked == true) {
selectedIds.push(ids[i].value);
}
}
}
In HTML:
Master Check box <input type="checkbox" onClick="toggle(this);">
Other Check boxes <input type="checkbox" name="ALL">
You can use the :first selector to find the first input and bind the change event to it. In my example below I use the :checked state of the first input to define the state of it's siblings. I would also suggest to put the code in the JQuery ready event.
$('document').ready(function(){
$('#ScrollCB input:first').bind('change', function() {
var first = $(this);
first.siblings().attr('checked', first.is(':checked'));
});
});
I am not sure why you would use a label when you have a name on the checkbox. Use that as the selector. Plus your code has no labels in the HTML markup so it will not find anything.
Here is the basic idea
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings().prop("checked",this.checked);
});
if there are other elements that are siblings, than you would beed to filter the siblings
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings(":checkbox").prop("checked",this.checked);
});
jsFiddle

Check the first checkbox, if no checkbox is selected

I have this HTML code
<input type="checkbox" name="city_pref[]" id="city_all" value="0" checked /><label for="city_all">All</label>
<input type="checkbox" name="city_pref[]" id="city_pref_1" value="Chicago" /><label for="city_pref_1">Chicago</label>
<input type="checkbox" name="city_pref[]" id="city_pref_2" value="Texas" /><label for="city_pref_2">Texas</label>
And, I have placed my code in a fiddle, which is working correctly. What I really want to do is, when none of the checkboxes are selected, then I want the all checkbox to get selected automatically.
try the following:
$('input[type=checkbox]').change(function(){
if ($('input[type=checkbox]:checked').length == 0) {
$('#city_all').prop('checked', true)
}
})
DEMO
$('input[type="checkbox"]').change(function(){
if($('input[type="checkbox"]:checked').length == 0)
$('#city_all').attr('checked', 'checked');
});
All you really need is one line ?
$('input[type="checkbox"][name="city_pref[]"]').on('change', function(e){
this.checked ? $(this).siblings('[name="city_pref[]"]').prop('checked', false) : $("#city_all").prop('checked', true);
});
FIDDLE

Categories

Resources