All / none checkbox - javascript

Why doesn't this "All / none" option do his job? I can't see why .attr('checked', status); doesn't toggle all the checkboxes.
And what's the most clever way to hide / show elements of #main belonging to selected categories?
$('input[name="all"]').click(function() {
var status = $(this).is(':checked');
alert(status);
$('input[type="checkbox"]').attr('checked', status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label>
<input type="checkbox" name="all" checked="true">
All / none
</label>
<label>
<input type="checkbox" name="cat1" checked="true">
A
</label>
<label>
<input type="checkbox" name="cat2">
B
</label>
<label>
<input type="checkbox" name="cat3">
C
</label>
<label>
<input type="checkbox" name="cat4">
D
</label>

Use .prop() not .attr()
See http://api.jquery.com/prop/
$('input[name="all"]').click(function(){ var status = $(this).is(':checked'); alert(status); $('input[type="checkbox"]').prop('checked', status); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox" name="all" checked="true">All / none</label>
<label><input type="checkbox" name="cat1" checked="true">A</label>
<label><input type="checkbox" name="cat2">B</label>
<label><input type="checkbox" name="cat3">C</label>
<label><input type="checkbox" name="cat4">D</label>

As mentioned here, you should make use of jQuery's .prop() function for checking/unchecking checkbox elements.
So try to change your handler like so:
$('input[name="all"]').click(function(){
var status = !!$(this).prop('checked');
alert(status);
$('input[type="checkbox"]').prop('checked', status);
});
To hide/show elements, I recommend iterating over each one:
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('name');
var status = !!$(this).prop('checked');
if (status) {
$('#main').find('.' + name).show();
} else {
$('#main').find('.' + name).hide();
}
});
Regarding your last question for coloring, I'd recommend using a class, say for example gray.
var total = $('input[type="checkbox"]').not('[name=all]').length;
var count = $('input[type="checkbox"]:checked').not('[name=all]').length;
if (count === total) {
$('input[name="all"]').removeClass('gray');
} else {
$('input[name="all"]').addClass('gray');
}

This sets the checkboxes and the div visibility as needed.
It uses opacity to simulate a grayed-out checkbox.
$('[name="all"]').click(function() { //set all checkboxes to match All / none
$(':checkbox')
.prop('checked', this.checked)
.change();
});
$('input')
.change(function() { //show divs corresponding to checked input
var checked= $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name)
.toggle(this.checked);
$('[name="all"]')
.prop('checked', checked > 0)
.toggleClass('someChecked', checked && checked<$(':checkbox:not([name="all"])').length);
})
.change(); //run the method immediately
$('[name="all"]').click(function() { //set all checkboxes to match All / none
$(':checkbox')
.prop('checked', this.checked)
.change();
});
$('input')
.change(function() { //show divs corresponding to checked input
var checked= $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name)
.toggle(this.checked);
$('[name="all"]')
.prop('checked', checked > 0)
.toggleClass('someChecked', checked && checked<$(':checkbox:not([name="all"])').length);
})
.change(); //run the method immediately
.someChecked {
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label>
<input type="checkbox" name="all" checked="true">
All / none
</label>
<label>
<input type="checkbox" name="cat1" checked="true">
A
</label>
<label>
<input type="checkbox" name="cat2">
B
</label>
<label>
<input type="checkbox" name="cat3">
C
</label>
<label>
<input type="checkbox" name="cat4">
D
</label>

// Bind also the single checkboxes to show/hide the elements in div
$('input[type = "checkbox"]').click(function(){
if($(this).prop('checked'))
$('div.' + $(this).attr('name')).show();
else
$('div.' + $(this).attr('name')).hide();
});
$('input[name="all"]').click(function(){
var status = $(this).is(':checked');
alert(status);
$('input[type="checkbox"]').each(function(){
$(this).prop('checked', status);
if(!status)
$('div.' + $(this).attr('name')).hide();
else
$('div.' + $(this).attr('name')).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label><input type="checkbox" name="all" checked="true">All / none</label>
<label><input type="checkbox" name="cat1" checked="true">A</label>
<label><input type="checkbox" name="cat2">B</label>
<label><input type="checkbox" name="cat3">C</label>
<label><input type="checkbox" name="cat4">D</label>

All answers here were great. Just for future reference, I post the one I'll use (which is a mix of #RickHitchcock's and the usage of indeterminate state of a checkbox) :
$('input[name="all"]').click(function() { $(':checkbox').prop('checked', this.checked).change(); });
$('input[type="checkbox"]').change(function() {
var checked = $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name).toggle(this.checked);
$('input[name="all"]').prop('checked', checked > 0)
.prop('indeterminate', checked && checked < $(':checkbox:not([name="all"])').length);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label><input type="checkbox" name="all" checked>All / none</label>
<label><input type="checkbox" name="cat1" checked>A</label>
<label><input type="checkbox" name="cat2" checked>B</label>
<label><input type="checkbox" name="cat3" checked>C</label>
<label><input type="checkbox" name="cat4" checked>D</label>

Related

Want to get the value of checkbox and assign it's value to the class-name

In a div, I have a 'select all' checkbox. When this checkbox is checked, all the other checkboxes will automatically checked. I want to assign their values as a class name. I am able to achieve this when a single checkbox is checked. But now I want this should work when all checkbox is checked at once when a select-all checkbox is checked. ​
$('.select-all').on('click', function() {
let isSelected = $(this).is(':checked');
$(this).parents('.checkbox-list').find('input[type="checkbox"]').not('.select-all').each(function() {
if (isSelected) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
})
});
$('input:checkbox').not('.select-all').change(function() {
var cl = $(this).val();
var cls = 'abc' + '' + cl + '';
if ($(this).is(':checked')) {
$(this).addClass(cls);
} else {
$(this).removeClass(cls);
}
})
<div class="checkbox-list">
<label><input type="checkbox" class="select-all" name="">All</label>
<label><input type="checkbox" name="" value="1">One</label>
<label><input type="checkbox" name="" value="2">Two</label>
<label><input type="checkbox" name="" value="3">Three</label>
<label><input type="checkbox" name="" value="4">Four</label>
<label><input type="checkbox" name="" value="5">Five</label>
<label><input type="checkbox" name="" value="6">Six</label>
<label><input type="checkbox" name="" value="6">Three</label>
<label><input type="checkbox" name="" value="7">Four</label>
<label><input type="checkbox" name="" value="8">Five</label>
<label><input type="checkbox" name="" value="9">Six</label>
</div>
You pretty much wrote the code already to achieve this,
What i did here is adding the cl = $(this).val(); and cls = 'abc' + '' + cl + ''; in the each loop and add the class when isSelected is true, and delete when false.
$('.select-all').on('click', function() {
let isSelected = $(this).is(':checked');
$(this).parents('.checkbox-list').find('input[type="checkbox"]').not('.select-all').each(function() {
let cl = $(this).val();
let cls = 'abc' + '' + cl + '';
if (isSelected) {
$(this).prop('checked', true);
$(this).addClass(cls);
} else {
$(this).prop('checked', false);
$(this).removeClass(cls);
}
})
});
$('input:checkbox').not('.select-all').change(function() {
let cl = $(this).val();
let cls = 'abc' + '' + cl + '';
if ($(this).is(':checked')) {
$(this).addClass(cls);
} else {
$(this).removeClass(cls);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox-list">
<label><input type="checkbox" class="select-all" name="">All</label>
<label><input type="checkbox" name="" value="1">One</label>
<label><input type="checkbox" name="" value="2">Two</label>
<label><input type="checkbox" name="" value="3">Three</label>
<label><input type="checkbox" name="" value="4">Four</label>
<label><input type="checkbox" name="" value="5">Five</label>
<label><input type="checkbox" name="" value="6">Six</label>
<label><input type="checkbox" name="" value="6">Three</label>
<label><input type="checkbox" name="" value="7">Four</label>
<label><input type="checkbox" name="" value="8">Five</label>
<label><input type="checkbox" name="" value="9">Six</label>
</div>

jQuery form submit button goes to URL based on checkbox selected

I have a simple contact form with multiple checkboxes, when a user selects a checkbox it should go to the url/folder tied to the url that's in the value. The current problem is after a user checks the checkbox and clicks submit, then goes back to that page and the checkbox resets, the submit button still takes them to the previously selected checkbox.
Need a way to fully reset the form and disable the button so the submission doesn't get too confusing for the user. Thanks!
Here is my form code:
<form name="frm" id="myForm" method="post" >
<div class="provider-checkboxes">
<input type="checkbox" name="rGroup" id="r1" value="folder-1/" onclick="formaction(this)"/>
<label class="check-div" for="r1">Label 1</label>
<input type="checkbox" name="rGroup" id="r2" value="folder-2/" onclick="formaction(this)"/>
<label class="check-div" for="r2">Label 2</label>
<input type="checkbox" name="rGroup" id="r3" value="folder-3/" onclick="formaction(this)"/>
<label class="check-div" for="r3">Label 3</label>
<button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</div>
</form>
Here is the script:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
});
});
$('[data-toggle="btns"] .btn').on('click', function(){
var $this = $(this);
$this.parent().find('.active').removeClass('active');
$this.addClass('active');
});
$('.selectme input:checkbox').click(function() {
$('.selectme input:checkbox').not(this).prop('checked', false);
});
$('.provider-checkboxes input:checkbox').click(function() {
$('.provider-checkboxes input:checkbox').not(this).prop('checked', false);
});
function formaction(checkbox){
document.getElementById("myForm").action = checkbox.value;;
}
function UncheckAll(){
var w = document.getElementsByTagName('input');
for(var i = 0; i < w.length; i++){
if(w[i].type=='checkbox'){
w[i].checked = false;
}
}
}
Consider the following code. Think this will help, based on what you have shared.
$(function() {
function setFormAction(frm, a) {
frm.attr("action", a);
}
function unCheckAll() {
$("input[type='checkbox']").prop("checked", false);
$(".provider-checkboxes .btn").hide();
}
$('.provider-checkboxes input:checkbox').click(function() {
unCheckAll();
$(this).prop("checked", true);
$(".provider-checkboxes .btn").toggle(300);
setFormAction($("#myForm"), "./" + $(this).val());
console.log($("#myForm")[0]);
});
unCheckAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="frm" id="myForm" method="post">
<div class="provider-checkboxes">
<input type="checkbox" name="rGroup" id="r1" value="folder-1/" />
<label class="check-div" for="r1">Label 1</label>
<input type="checkbox" name="rGroup" id="r2" value="folder-2/" />
<label class="check-div" for="r2">Label 2</label>
<input type="checkbox" name="rGroup" id="r3" value="folder-3/" />
<label class="check-div" for="r3">Label 3</label>
<button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</div>
</form>

Label -> Checkbox Text

I have this problem..
I have this HTML code for 2 groups of checkbox:
<label class="checkbox"><input type="checkbox" onClick="toggle_colors(this)" checked><i></i>All Colors</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox"><input type="checkbox" onClick="toggle_brands(this)" checked><i></i>Tutte le Marche</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Asus</label>
And I use this javascripts for select all/toggle all:
function toggle_brands(source) {
checkboxes = document.getElementsByName('brand');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function toggle_colors(source) {
checkboxes = document.getElementsByName('colore');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
When the user click on the checkbox I need to know if the checkbox is selected or not, to send the details of the query by AJAX..
To know if the checkbox I use this javascript:
$( "[type=checkbox]" ).change(function() {
if(this.checked) {
alert('checked');
}
else {
alert('unchecked');
}
});
I want the text at the right of the selected checkbox..!
Ok.. With the parent work fine!
I have added this code to create the query:
function create_query(){
var query = "SELECT * FROM computers ORDER BY " + ($("#ordine option:selected").val()) + " LIMIT " + ($("#risultati option:selected").val());
$.ajax({
type: "POST",
url: "static/cerca_prodotti.php",
data: "query="+query,
dataType: "html",
success: function(risposta){
$("div#risultati").html(risposta);
},
})
}
$( "[type=checkbox]" ).change(function() {
if(this.checked) {}
else {}
});
$("#ordine").change(function() {
create_query();
});
But I need to modify the query when the checkbox was checked/unchecked!
When you change the checked property programatically, the change event will not get triggered, you need to trigger the event manually.
$('input[data-all-type]').change(function() {
$('input[name="' + $(this).data('allType') + '"]')[this.checked ? 'not' : 'filter'](':checked').prop('checked', this.checked).change();
})
$("input[type=checkbox]:not([data-all-type])").change(function() {
if (this.checked) {
console.log('checked', this);
} else {
console.log('unchecked', this);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" name="color-all" data-all-type="colore"><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" name="brand-all" data-all-type="brand"><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Asus</label>
You can do that with only one function
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', $(source).is(':checked'))
//OR
$('input[name="' + things + '"]').prop('checked', source.checked);
}
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', source.checked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'colore')" checked><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'brand')" checked><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Asus</label>
You can get text of the parent node of the checkbox in this way:
$( "[type=checkbox]" ).change(function() {
var text = this.parentElement.innerText;
if(this.checked) {
alert(text + ': checked');
}
else {
alert(text + ': unchecked');
}
});

Get only two values of multiple Checkboxes

I found this code on codeLAB and I'm trying to get true result only if "Cricket" and "Boxing" are checked. Currently it works if both of them are checked, but also when the others are selected.
https://jsfiddle.net/kubus1234/oksm8eaw/
$("button").click(function() {
var favorite = [];
$.each($("input[name='sport']:checked"), function() {
favorite.push($(this).val());
});
var test = [];
$.each($("input[name='sport']:checked"), function() {
test.push($(this).val());
});
if (favorite[1] == "cricket" || test[1] == "boxing") {
alert("Your are the best");
} else {
alert("Your are looser");
}
});
Any solution?
Not sure why you traversed the selected checkboxes twice, but here's one way to get your results:
$(document).ready(function() {
$("button").click(function() {
var selected = $("input[name='sport']:checked").toArray().map(function(checkbox) {
return $(checkbox).val();
});
if (selected.length === 2 && selected[0] === "cricket" && selected[1] === "boxing") {
alert("You are the best");
} else {
alert("You lose");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h3>Select your favorite sports:</h3>
<label>
<input type="checkbox" value="football" name="sport">Football</label>
<label>
<input type="checkbox" value="baseball" name="sport">Baseball</label>
<label>
<input type="checkbox" value="cricket" name="sport">Cricket</label>
<label>
<input type="checkbox" value="boxing" name="sport">Boxing</label>
<label>
<input type="checkbox" value="racing" name="sport">Racing</label>
<label>
<input type="checkbox" value="swimming" name="sport">Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
This would be easily researchable but I'll post a solution anyway
1) I gave the checkboxes ids
2) I changed the JavaScript to check if both checkboxes are checked at once with .is(":checked")
<form>
<h3>Select your favorite sports:</h3>
<label><input type="checkbox" id="chkFootball" value="football" name="sport"> Football</label>
<label><input type="checkbox" id="chkBaseball" value="baseball" name="sport"> Baseball</label>
<label><input type="checkbox" id="chkCricket" value="cricket" name="sport"> Cricket</label>
<label><input type="checkbox" id="chkBoxing" value="boxing" name="sport"> Boxing</label>
<label><input type="checkbox" id="chkRacing" value="racing" name="sport"> Racing</label>
<label><input type="checkbox" id="chkSwimming" value="swimming" name="sport"> Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
$(document).ready(function() {
$("button").click(function(){
if ($('#chkCricket').is(':checked') && $('#chkBoxing').is(':checked')) {
alert("Checked");
}
else {
alert("Not checked");
}
});
});
https://jsfiddle.net/oksm8eaw/2/
Please don't use javascript alerts. Alerts cause cancer...
... instead use ids, and jQuery html(): add this to the HTML: <div id="result"></div>
Solution
$(document).ready(function() {
$("button").click(function(){
var matchCount = 0;
$('input').each(function(){
if( this.value == "cricket" || this.value == "boxing") {
if(this.checked) matchCount++;
}
});
if(matchCount>1){
$("#result").html("YUP!");
} else {
$("#result").html("NOPE!");
}
});
});

Select children elements based on class in iteration

Either using Vanilla Javascript or jQuery.
// html
<input type="checkbox" value="1" checked="checked" name="patient[event_type_ids][]" id="patient_event_type_ids_1"> Bleeding puncture
<div data-target="patient_event_type_ids_1" class="form-sub">
<div class="form-group">
<input type="radio" value="true" name="patient[blood_aspirated]" id="patient_blood_aspirated_true"> Yes
<input type="radio" value="false" checked="checked" name="patient[blood_aspirated]" id="patient_blood_aspirated_false"> No
</div>
<div class="form-group">
<input type="radio" value="positive" name="patient[iv_test]" id="patient_iv_test_positive"> Positive
<input type="radio" value="negative" checked="checked" name="patient[iv_test]" id="patient_iv_test_negative"> Negative
</div>
</div>
<input type="checkbox" value="1" checked="checked" name="patient[event_type_ids][]" id="patient_event_type_ids_2"> Vascular puncture
<div data-target="patient_event_type_ids_2" class="form-sub">
<div class="form-group">
<input type="radio" value="true" name="patient[abc]" id="patient_abc_true"> Yes
<input type="radio" value="false" checked="checked" name="patient[abc]" id="patient_abc_false"> No
</div>
<div class="form-group">
<input type="radio" value="positive" name="patient[xyz]" id="patient_xyz_positive"> Positive
<input type="radio" value="negative" checked="checked" name="patient[xyz]" id="patient_xyz_negative"> Negative
</div>
</div>
// javascript
var subForms = $('.form-sub');
subForms.each(function() {
var subForm = this;
var parentForm = '#' + subForm.dataset.target;
if ($(parentForm).prop('checked')) {
$(subForm).show();
} else {
$(subForm).hide();
}
$(parentForm).change(function(){
if($(this).prop("checked")) {
$(subForm).show();
} else {
$(subForm).hide();
$(':input')
.not(':button, :submit, :reset, :hidden')
.removeAttr('checked')
.removeAttr('selected')
.not(':checkbox, :radio, select')
.val('');
}
});
});
I want to clear all input when the checkbox is unchecked. The line $(':input') is definitely, but that's where I should select the responding inputs which are the children of .form-sub. How do I do that in Javascript?
replace this line
var parentForm = '#' + subForm.dataset.target;
by
var parentForm = $( subForm ).prev();
and update the change event as
if ( parentForm.prop('checked')) {
$(subForm).show();
} else {
$(subForm).hide();
}
parentForm.change(function(){
if($(this).prop("checked")) {
$(subForm).show();
} else {
$(subForm).find(':input')
.not(':button, :submit, :reset, :hidden')
.removeAttr('checked')
.removeAttr('selected')
.not(':checkbox, :radio, select')
.val('');
$(subForm).hide();
}
});

Categories

Resources