I have a dynamic list of checkboxes all with the same class. I want to disable the submit button until all checkboxes in the class "group1" has been selected.
I also only want to do this, when this class is present on the page.
I was did that part this way:
<input type="checkbox" class="group1" value="20" />
<input type="checkbox" class="group1" value="15" />
<input type="checkbox" class="group1" value="14" />
if ($(".group1").length > 0) {
//run below code
}
So I started like this, but am unsure of how to know when, all the checkboxes of that class are selected.
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
var checkboxes = $('.group1');
if($(this).is(':checked')) {
//if all chekced, enable submit button
$(':input[type="submit"]').prop('disabled', false);
} else {
$(':input[type="submit"]').prop('disabled', true);
}
}
});
});
I have seen this jQuery Array of all selected checkboxes (by class), but as the class can be of any length, I dont know how to check that all are selected.
The easiest way to do this is to compare the total number of checkboxes to the number which are checked, like this:
var $group = $('.group1');
$(':input[type="submit"]').prop('disabled', $group.length != $group.filter(':checked').length);
You can simply check like this, total number of checkboxes and total number of checked checkboxes:
if ($('.group1').length == $('.group1:checked').length) {
// all are checked...
$(':input[type="submit"]').prop('disabled', false);
} else {
$(':input[type="submit"]').prop('disabled', true);
}
var selected = $(".group1:checked").length;
Count the checkboxes wich are checked.
First you will need to bind an event to checkboxes, to every time they change state to re-run the check to enable or disable the button;
Then you can check if all checkboxes are checked comparing the length of your group vs the length of your group filtered by :checked pseudo selector
And to change the state of the submit button, you can use .prop method, that accept an attribute and a state of this attribute as a second parameter. So:
$group1 = $(".group1");
$submit = $('[type=submit]');
if ($group1.length > 0) {
$group1.on('change', checkBoxes)
}
function checkBoxes(){
var $checked = $group1.filter(':checked');
$submit.prop('disabled', $group1.length != $checked.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="group1" value="20" />
<input type="checkbox" class="group1" value="15" />
<input type="checkbox" class="group1" value="14" />
<input type="submit" disabled>
Related
I have two checkboxes on a page and I want them to act as only one. For example, I select one, and the other is selected automatically, and vice-versa.
I've managed to select both of them at once, but I can't seem to figure out a way to deselect them at once.
And what's bothering me the most, is that it's probably a super simple line of code that I'm simply not remembering.
Is there a way to do this?
Is this what you're looking for?
$(".test").change(function () {
$(".test").attr("checked", this.checked);
});
<input type='checkbox' class='test'>A<br />
<input type='checkbox' class='test'>B<br />
Here is a solution in pure javascript:
// Select all checkboxes using `.checkbox` class
var checkboxes = document.querySelectorAll('.checkbox');
// Loop through the checkboxes list
checkboxes.forEach(function (checkbox) {
// Then, add `change` event on each checkbox
checkbox.addEventListener('change', function(event) {
// When the change event fire,
// Loop through the checkboxes list and update the value
checkboxes.forEach(function (checkbox) {
checkbox.checked = event.target.checked;
});
});
});
<label><input type="checkbox" class="checkbox"> Item 1</label>
<br>
<label><input type="checkbox" class="checkbox"> Item 2</label>
$(document).ready(function() {
$('#check_one').change(function() {
$('#check_two').prop('checked', $('#check_one').prop('checked'));
});
$('#check_two').change(function() {
$('#check_one').prop('checked', $('#check_two').prop('checked'));
});
});
<form>
<label>Simple checkbox</label>
<input type="checkbox" id="check_one" />
<label>Complicated checkbox</label>
<input type="checkbox" id="check_two" />
</form>
Assuming you have two checkboxes named differently but working in concert, this code would work
html:
<input type="checkbox" id="1" class="handleAsOne">
<input type="checkbox" id="2" class="handleAsOne">
javascript (jquery):
$('.handleAsOne').on('change'){
$('.handleAsOne').prop('checked', false);
$(this).prop('checked', true);
}
if i understood your question correctly you are looking for something like this.
All I want is to check / uncheck all of the choices with one check button.
<form action="process.php" method="post">
<p> Select pet: </p>
<p> <input type="checkbox" name="dog" value="dog"> Dog </p>
<p> <input type="checkbox" name="cat" value="cat"> Cat </p>
<p> <input type="checkbox" name="bird" value="Tbird"> Bird </p>
<p> <input type="checkbox" name="checkall" value="checkall"> All </p>
what code / codes am I missing? I need "All" to uncheck / check all choices if it is chosen by the user. I use xampp for this one.
You can do something like this (jQuery):
$("#checkall").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Just add the id attribute to the checkbox:
<input type="checkbox" id="checkall" name="checkall" value="checkall">
Create a class for you checkboxes and use Javascript:
<form .....>
<input type="checkbox" class="myCheckboxes" name="dog" value="dog" />
<!--rest of the checkboxes with the same class name but different names and values follow-->
<button type="button" class="checkedAll">Check All</button>
</form>
<script type="text/javascript">
(function() {
var checked = false;
$('button.checkedAll').click(function() {
checked = !checked;
$('.myCheckboxes').prop('checked', checked);
if (checked) $(this).text('Uncheck All');
else $(this).text('Check All);
});
})();
</script>
If you add an id attribute with the value "petForm" to your form element.
<form id="petForm" action="process.php" method="post">
You can use the following pure Javascript.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById("petForm");
if (form) {
var checkAll = form.querySelector("input[type='checkbox'][name='checkall']");
var checkBoxes = form.querySelectorAll("input[type='checkbox']:not([name='checkall'])");
checkAll.addEventListener("change", function(e) {
for (checkBox of checkBoxes) {
checkBox.checked = this.checked;
}
});
}
}
</script>
It adds an event listener to the document that waits for the DOM to be loaded, then identifies the form by the added id attribute. If it finds the form, then it stores the "checkall" input element and all the other input elements of type checkbox in the form in two different variables. After that it adds an on change event listener to the "checkall" checkbox input element that sets all other checkbox input elements in the form to the same value as the checkall checkbox input element.
Here's a JSFiddle of the code above running.
If your form contains additional checkboxes that you don't want checked by the checkall checkbox, you'll need to modify the way checkBoxes is populated. Similarly if you have multiple collections of checkboxes then you'll need to find a way to differentiate between them.
I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')
What method would be best to use to selectively set a single or multiple radio button(s) to a desired setting with JavaScript?
Very simple
radiobtn = document.getElementById("theid");
radiobtn.checked = true;
the form
<form name="teenageMutant">
<input value="aa" type="radio" name="ninjaTurtles"/>
<input value="bb" type="radio" name="ninjaTurtles"/>
<input value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" will be checked by default, if you remove the "checked" non of the boxes will be checked when the form is first loaded.
document.teenageMutant.ninjaTurtles[0].checked=true;
now value="aa" is checked. The other radio check boxes are unchecked.
see it in action: http://jsfiddle.net/yaArr/
You may do the same using the form id and the radio button id. Here is a form with id's.
<form id="lizardPeople" name="teenageMutant">
<input id="dinosaurs" value="aa" type="radio" name="ninjaTurtles"/>
<input id="elephant" value="bb" type="radio" name="ninjaTurtles"/>
<input id="dodoBird" value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" is checked by default.
document.forms["lizardPeople"]["dinosaurs"].checked=true;
now value="aa" with id="dinosaurs" is checked, just like before.
See it in action: http://jsfiddle.net/jPfXS/
Vanilla Javascript:
yourRadioButton.checked = true;
jQuery:
$('input[name=foo]').prop('checked', true);
or
$("input:checkbox").val() == "true"
You can also explicitly set value of radio button:
<form name="gendersForm">
<input type="radio" name="gender" value="M" /> Man
<input type="radio" name="gender" value="F" /> Woman
</form>
with the following script:
document.gendersForm.gender.value="F";
and corresponding radio button will be checked automatically.
Look at the example on JSFiddle.
/**
* setCheckedValueOfRadioButtonGroup
* #param {html input type=radio} vRadioObj
* #param {the radiobutton with this value will be checked} vValue
*/
function setCheckedValueOfRadioButtonGroup(vRadioObj, vValue) {
var radios = document.getElementsByName(vRadioObj.name);
for (var j = 0; j < radios.length; j++) {
if (radios[j].value == vValue) {
radios[j].checked = true;
break;
}
}
}
Try
myRadio.checked=true
<input type="radio" id="myRadio">My radio<br>
$("#id_of_radiobutton").prop("checked", true);
I am configuring a radio button within a document fragment and tried using radiobtn.checked = true;.
That didn't work so I instead went with this solution:
radiobtn.setAttribute("checked", "checked");
This sets checked using name to cycle through the elements and a value check to set the desired element to true. I kept it as simple as possible, its pretty easy to put it into a function or a loop, etc.
variable 'nameValue' is the radio elements name value
variable 'value' when matched sets the radio button
Array.from( document.querySelectorAll('[name="' + nameValue + '"]') ).forEach((element,index) =>
{
if (value === element.value) {
element.checked = true;
} else {
element.checked = false;
}
});
How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if not selected.
<div id="selected-people"></div>
<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />
Is it possible to extract the id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.
I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.
function storeuser()
{
var users = [];
$('input[type=checkbox]:checked').each(function()
{
users.push($(this).val());
});
$('#selected-people').html(users)
}
$(function()
{
$('input[type=checkbox]').click(storeuser);
storeuser();
});
So you want to keep the DIV updated whenever a checkbox is clicked? That sound right?
http://jsfiddle.net/HBXvy/
var $checkboxes;
function storeuser() {
var users = $checkboxes.map(function() {
if(this.checked) return this.id;
}).get().join(',');
$('#selected-people').html(users);
}
$(function() {
$checkboxes = $('input:checkbox').change(storeuser);
});
Supposing you only have these input controls on page I can write following code.
$.each($('input'), function(index, value) {
$('selected-people').append($(value).attr('id'));
});
Edited Due to More Description
$(document).ready(function() {
$.each($('input'), function(index, value) {
$(value).bind('click', function() {
$('selected-people').append($(value).attr('id'));
});
});
});
Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.
Change:
users.push($(this).val());
to:
users.push($(this).attr('id'));
This is for to bind the comma seperated values to input checkbox list
$(".chkboxes").val("1,2,3,4,5,6".split(','));
it will bind checkboxes according to given string value in comma seperated.