Select/Deselect All dynamic checkboxes in Rails 4 with Javascript - javascript

I have followed this StackOverflow Question's Answer1 and Answer2
but not getting result.. As I am calling all checkbox list's data from Range tabel. and their id is also defined by data.. Let me show you the code for this screenshot
= f.collection_check_boxes :range_ids, Range.active, :id, :name, {},:class=>'checkbox'
which returns as
<input id="campaign_range_ids_1" class="checkbox" type="checkbox" value="1" name="campaign[range_ids][]">
<input id="campaign_range_ids_2" class="checkbox" type="checkbox" value="2" name="campaign[range_ids][]">
<input id="campaign_range_ids_3" class="checkbox" type="checkbox" value="3" name="campaign[range_ids][]">
<input id="campaign_range_ids_4" class="checkbox" type="checkbox" value="4" name="campaign[range_ids][]">
I want if All means id="campaign_range_ids_4" is selected/deselected then all other check-boxes should be perform accordingly..
Here also have a screenshot of Range Table
I had tried this Javascript
:javascript
$('#campaign_range_ids_4').click(function() {
if(this.checked) {
$('#campaign_range_ids_1').checked = true;
$('#campaign_range_ids_2').checked = true;
$('#campaign_range_ids_3').checked = true;
});
} else {
$('#campaign_range_ids_1').checked = false;
$('#campaign_range_ids_2').checked = false;
$('#campaign_range_ids_3').checked = false;
});
}
});
Please correct me where I do Mistake.... Thanks in advance.. :)
Updated Question
I have followed Shridhar's and Pavan's answer it works perfectly but now I want that when I select All then deselect any one then it must uncheck "All" (4th checkbox) but it remains as it is..

As i said,it should be $('#campaign_range_ids_4') not $('#campaign_beacon_range_ids_4')
This will work too
$('#campaign_range_ids_4').click(function() {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
Demo

Error in Selectors ,It should be $('#campaign_range_ids_4') not $('#campaign_beacon_range_ids_4') use prop() to set the checkbox state
Try this
$('#campaign_range_ids_4').click(function () {
if ($(this).is(':checked')) {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', true);
} else {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', false);
}
});
DEMO
OR
$('#campaign_range_ids_4').click(function () {
$('#campaign_range_ids_1, #campaign_range_ids_2, #campaign_range_ids_3').prop('checked', $(this).is(':checked'));
});
DEMO

change the selector to $('#campaign_range_ids_4')and do this:
$('#campaign_range_ids_4').change(function() {
$('#campaign_range_ids_1, #campaign_range_ids_2, #campaign_range_ids_3').prop('checked', this.checked);
});
instead of click use change method.

Modifying Sridhar's answer finally I got the Answer of my Updated Question's.
I wanted if All(4th checkbox) is checked then all check-box should be selected and if it's unchecked then all check-box should be unchecked it works perfectly
But Issue I had found that If All(4th checkbox) is selected then it check all boxes then if I unchecked any check-box then All(4th checkbox) must be uncheked which was not occur.
Solution by Modifying Code: In future if other people face the same issue..
HTML Code:
<input id="campaign_range_ids_1" class="checkbox" type="checkbox" value="1" name="campaign[range_ids][]">London
<input id="campaign_range_ids_2" class="checkbox" type="checkbox" value="2" name="campaign[range_ids][]">India
<input id="campaign_range_ids_3" class="checkbox" type="checkbox" value="3" name="campaign[range_ids][]">USA
<input id="campaign_range_ids_4" class="checkbox" type="checkbox" value="4" name="campaign[range_ids][]">All
JavaScript:
$('#campaign_range_ids_4').click(function () {
if ($(this).is(':checked')) {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', true);
} else {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', false);
}
});
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').click(function () {
if ($(this).is(':checked')) {
} else {
$('#campaign_range_ids_4').prop('checked', false);
}
});
Working Demo:

Related

JQuery selective hiding not working

I'm trying to create a menu where each element has its own checkbox. On selecting the sorting button ( for now it is a checkbox here ), the menu is supposed to show only the elements who already have the checkboxes active ( this is done by manually clicking the checkbox of the element and keeping it active)
Here's my HTML code
<input type= "checkbox" class="toggler" id="clicked" onclick="tclick()" >click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello3</p>
And here is my Jquery
function but_clicked(){
// alert("Hello, checkbox clicked");
if(this.id=="active"){
this.id="inactive";
console.log(this.id);}
else{
this.id="active";
console.log(this.id);
}
}
function tclick(){
//alert("Toggler clicked");
if(this.id=="clicked"){
this.id="empty";
console.log(this.id);
}
else{
this.id="clicked";
console.log(this.id);
}
}
$(document).ready(function(){
$('.toggler').change(function(){
if($(this).is('clicked')){
$('#inactive').hide();
$('#active').show();
}
else{
$('#active').show();
$('#inactive').show();
}
})
});
But when I am setting the Click here to sort checkbox, the others are not being hidden regardless of each of their checkbox status. I feel like it's a very silly mistake that I am doing, please help.
First of all id property must be unique in the DOM, so you cannot have multiple elements with id active or inactive.
This is the main problem as $('#inactive') will only return the first element it matches (since it should be unique).
Furthermore, checkboxes have a checked property that signifies if they are checked or not so all your code could just check that instead of altering the id all the time.
Last, you should use label tags for the text instead of p so that clicking on the text will also check/uncheck the checkbox.
(oh, the .toggler checkbox actually filters, and not sorts ,the others)
So taking all issues into account you could simplify your code to
$(document).ready(function() {
$('.toggler').change(function() {
if (this.checked) {
$('.grouped').parent().hide();
$('.grouped:checked').parent().show();
} else {
$('.grouped').parent().show();
}
})
});
label{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="toggler">click here to filter</label></p>
<label><input type="checkbox" class="grouped">Hello1</label>
<label><input type="checkbox" class="grouped">Hello2</label>
<label><input type="checkbox" class="grouped">Hello3</label>
Your code can be way easier with some little tricks.
First thing, do not change IDs at run time, it's a bad practise.
Checkboxes have properties like checked, which evaluates to false or true when tested with this.checked.
<input type= "checkbox" class="toggler" id="click_to_toggle" >click here to toggle
<p class="item"><input type="checkbox" >Hello1</p>
<p class="item"><input type="checkbox" >Hello2</p>
<p class="item"><input type="checkbox">Hello3</p>
And this is the only JS you need:
$('#click_to_toggle').on('change', function(){
if( this.checked ){
$('.item').hide();
$('.item input:checked').each(function(){
$(this).closest('.item').show();
});
} else {
$('.item').show();
}
});
Working fiddle HERE
Pass in the element itself this this in the html, and just use that parameter in your javascript instead of this. Also you need to use .is with the :checked selector instead of just clicked. I also change changed .changed() to .clicked() since they are the same event in this case. You also might want to consider changing the id of inactive/active to be a class since all ids must be unique.
function but_clicked(e) {
if (e.id == "active") {
e.id = "inactive";
console.log(e.id);
} else {
e.id = "active";
console.log(e.id);
}
}
function tclick(e) {
if (e.id == "clicked") {
e.id = "empty";
console.log(e.id);
} else {
e.id = "clicked";
console.log(e.id);
}
}
$(document).ready(function() {
$('.toggler').click(function() {
if($('.toggler').is(':checked')) {
$('#inactive').hide();
$('#active').show();
} else {
$('#active').show();
$('#inactive').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="toggler" id="clicked" onclick="tclick(this)">click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello3</p>

Checkbox check first time not working, after second time, it is OK

I am trying to create a checkbox with label. When user click the label, it will check if checkbox checked. The first time, I click the label, the box is checked, but no alert action. After I click the second time, it start to function, alert action happen. What did I do wrong. I have tried to use individual ID. Click not working either.
<script type="text/javascript">
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+ id_name).click(function(){
if ($('#'+id_name +'_checkbox').prop('checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
</script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
<script type="text/javascript">
$('label').click(function() {
if ($('#'+ $(this).attr('id') + '_checkbox').prop('checked') === false) {
alert('Checked');
}
else {
alert('Unchecked');
}
});
</script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
Also be sure, you have included jQuery library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
And in new version of jQuery you can use insted of this:
if ($('#'+ $(this).attr('id') + '_checkbox').prop('checked') === false) {
alert('Checked');
}
else {
alert('Unchecked');
}
This piece of code:
// Just be careful, its inverted. Because, when you click label to check checkbox, the checkbox is still unchecked, and after alert will be checked...
if ($('#'+ $(this).attr('id') + '_checkbox').is(':checked') {
alert('Unchecked');
}
else {
alert('Checked');
}
Workind DEMO here in jsFiddle
Simplify things, you don't need each loop:
$('label').click(function() {
name=this.id;
if ($('#'+name+'_checkbox').prop('checked')) {
alert('Checked');
}
else{
alert('unchecked');
}
});
Demo: http://jsfiddle.net/fqvajvo1/2/
Script running correctly, script checks prop, but on label click -> checkbox is really unchecked, property changing comes later.
So, maybe in your case reverse logic could help (if you need alerts at all):
http://jsfiddle.net/fqvajvo1/4/ :)
I always use .is(':checked').I find it way more reliable
<script type="text/javascript">
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+id_name +'_checkbox').change(function(){
if ($(this).is(':checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
</script>
your click id is not complete name,so add complete name and call $(this) property will be ok...
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+ id_name+'_checkbox').click(function(){
if ($(this).prop('checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
Use .on to work for all events and all clicks on jQuery
Mainly used for dynamic creating elements
$(document).on('click','selector',function(){
});
Use class names for best options for grouped elements

jQuery - Checking Check Box Values (Chaining jQuery functions Vs If Statment)

I have multiple check boxes and wanting to get an overall value for them all.
For example if one is checked then value is true/selected.
If none are checked then false/unchecked.
My HTML is:
<input id="one" type="checkbox">
<input id="two" type="checkbox">
<input id="three" type="checkbox">
<input id="four" type="checkbox">
<button onclick="check();">Is checked (jQuery Chained)</button>
<button onclick="check2();">Is checked(Big If Statement)</button>
My JavaScript/jQuery is:
function check() {
var booleee = $('#one,#two,#three,#four').attr('checked');
alert("Checked: " + booleee);
}
function check2() {
if ($('#one').attr('checked') || $('#two').attr('checked') || $('#three').attr('checked') || $('#four').attr('checked')) {
alert("Checked: true");
}
alert("Checked: false");
}
Js Fiddle: Click Here
Please note, I have solved this problem. This question is more to help me understand why my checked2() function works and my check() doesnt.
var booleee = $('#one,#two,#three,#four').attr('checked'); checks only whether the first (in this case #one) checkbox is checked.
From the doc for attr
Get the value of an attribute for the first element in the set of
matched elements.
it should be
var booleee = $('#one,#two,#three,#four').filter(':checked').length > 0;
Also in new versions(>1.6) you need to use the property 'checked' (.prop('checked')) instead of attr in the alternative you have a :checked filter so .is(':checked').
Because it's not checking all the elements in the selector.
to make it work
function check() {
var booleee =$("input:checkbox:checked").length > 0;
alert("Checked: " + booleee);
}
To more specific selection add form id in selector
DEMO
A better approach: http://jsfiddle.net/arvind07/ZP78F/
function check() {
var checks = $('input:checkbox');
var checked = 0;
checks.each(function() {
if ($(this).is(":checked")) {
checked = 1;
return false;
}
});
if (checked) {
alert("Checked");
} else {
alert("Not checked");
}
}
in html set checked property
<input id="one" type="checkbox" checked="checked">
<input id="two" type="checkbox" checked="checked">
<input id="three" type="checkbox" checked="checked">
<input id="four" type="checkbox" checked="checked">
you not defined checked so it show undefined because it cant read this attribute and when you call second function then only false come in alert because their checkbox checked attribute not find
see demo
var checked = $(':checkbox:checked').length > 0;

checked radiobutton on checkbox change event

how we checked or unchecked all radiobutton on checkbox click.. if checkbox checked then all radiobutton also checked and vice versa.. it is not working properly
<input type="checkbox" id="Check" />SelectAll<br /><input type="radio"/>First<br />
<input type="radio"/>Second<br />
<input type="radio"/>Third<br />
<input type="radio"/>Fourth<br />
<input type="radio"/>Fifth</div>
<script>
var IsCheck = false;
$(document).ready(function () {
$("#Check").change(function () {
if (IsCheck == false) {
$("input[type=radio]").attr("checked", true);
IsCheck == true
}
else { $("input[type=radio]").attr("checked", false); IsCheck == false }
});
}); </script>
Take care you were just comparing operands instead of assigning to a variable in this statements:
IsCheck == true
^------ REMOVE ONE = so it's an assignment
Also, don't use .attr("checked", true); the correct form is:
$("input[type=radio]").attr("checked", 'checked'); //checking for jQuery < 1.6
And unchecking:
$("input[type=radio]").removeAttr("checked"); //unchecking for jQuery < 1.6
If you are using jQuery > 1.6 you can use the .prop() method with a boolean, which is similar to how you were trying to use it:
$("input[type=radio]").prop("checked", true); //checking for jQuery >= 1.6
$("input[type=radio]").prop("checked", false); //unchecking for jQuery >= 1.6
For jQuery 1.9 or higher use
$('input[type=radio]').prop("checked", true)
Otherwise try
$('input[type=radio]').attr('checked', 'checked');
Try this
$(document).ready(function () {
$("#Check").change(function () {
$("input[type=radio]").attr("checked", $("#Check").is(":checked"));
});
});
Demo
For your question, this could be the answer :
$("#Check").change(function () {
$("input:radio").prop("checked", this.checked);
});
Demo : http://jsfiddle.net/hungerpain/QSx29/
That said, radio buttons are not the best way of doing this. Its not semantically right. You can have only one radio button selected in a group. Try using checkboxes instead. Try to change you're markup to this :
<input type="checkbox" id="Check" />SelectAll
<br />
<input type="checkbox" />First
<br />
<input type="checkbox" />Second
<br />
<input type="checkbox" />Third
<br />
<input type="checkbox" />Fourth
<br />
<input type="checkbox" />Fifth</div>
And replace the JS code to this :
$("#Check").change(function () {
$("input:checkbox").prop("checked", this.checked);
});
Here's a demo : http://jsfiddle.net/hungerpain/QSx29/1/
You just need this
$("#Check").change(function () {
$("input[type=radio]").prop("checked", this.checked);
});
Demo ----> http://jsfiddle.net/kLnyD/
try this
http://jsfiddle.net/4u9sQ/
$("#Check").change(function () {
if ($(this).is(':checked')) {
$("input[type=radio]").prop("checked", true);
}
else { $("input[type=radio]").prop("checked", false); }
});

jQuery to check and uncheck checkboxes only fires once

I have a very simple requirement for my jQuery: to check a set of boxes if a radio button is checked, and to clear them all if another is checked.
The jquery works, however it only works once - that is if I click to check them all (all boxes check) and then click to clear them (all boxes clear), and then again click to check them all - there is no effect. Similarly if I manually uncheck some boxes then click to select all again, there is no effect.
jQuery
$('#all').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').attr('checked', false);
} else {
$('.country').attr('checked', true);
}
});
$('#none').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').attr('checked', true);
} else {
$('.country').attr('checked', false);
}
});
HTML
<div class="subselect">
<input type="radio" class="TLO" name="radio1" id="all" />Check All
<br />
<input type="radio" class="TLO" name="radio1" id="none" />Clear All
<br />
</div>
<br />
<br />
<div class="cselect" id="countries">
<input type="checkbox" class="country" />1
<br />
<input type="checkbox" class="country" />2
<br />
<input type="checkbox" class="country" />3
</div>
jsFiddle
http://jsfiddle.net/vsGtF/1/
Change your .attr() to .prop().
$('#all').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').prop('checked', false);
} else {
$('.country').prop('checked', true);
}
});
$('#none').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').prop('checked', true);
} else {
$('.country').prop('checked', false);
}
});
jsFiddle example
You could also reduce this to just:
$('#all').on('change', function () {
$('.country').prop('checked', $(this).is(':checked'));
});
$('#none').on('change', function () {
$('.country').prop('checked', !$(this).is(':checked'));
});
jsFiddle example
As the docs for .attr() state:
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. To retrieve and change DOM properties such as
the checked, selected, or disabled state of form elements, use the
.prop() method.
I know that this has been duped alot on here but I did miss something, I had:
id = $(this).attr('id');
if($('#checkbox_' + id).prop('checked')){
$('#checkbox_' + id).attr('checked', false);
} else {
$('#checkbox_' + id).attr('checked', true);
}
And as mentioned above ALL cases of attr need swapping for prop()
if($('#checkbox_' + id).prop('checked')){
$('#checkbox_' + id).prop('checked', false);
} else {
$('#checkbox_' + id).prop('checked', true);
}
Hope that helps somebody...

Categories

Resources