Checkbox select using querySelectorAll is not working - javascript

I have the following code, mostly from How can I select all checkboxes from a form using pure JavaScript and it's just not working.
Test.html
<html>
<head>
<script>
function select(){
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
}
</script>
</head>
<body>
<form id="myId" name="myForm">
<input type="checkbox" value="1"/> 1
<input type="checkbox" value="2"/> 2
<input type="checkbox" value="3"/> 3
<input type="button" onclick="select()" value="Select all"/>
</form>
</body>
</html>
Clicking the button does nothing.
I must be doing something really wrong here but I just can't pick it out.

Try this...
<html>
<head>
<script>
function test(){
var inputs = document.querySelectorAll("input[type='checkbox']");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
}
</script>
</head>
<body>
<form id="myId" name="myForm">
<input type="checkbox" value="1"/> 1
<input type="checkbox" value="2"/> 2
<input type="checkbox" value="3"/> 3
<input type="button" onclick="test()" value="Select all"/>
</form>
</body>
</html>

Try any other name for function select, rest your code is fine.

select is a native method defined on HTMLInputElement to focus selected input element.
select
Solution1: Change the name of your function.
Solution2: Try onclick="window.select()" insted of onclick="select()"

i suggest you To use Jquery and do like so :
Live Demo
HTML
<ul class="chk-container">
<li><button id="selecctall">select all</button>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li>
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li>
</ul>
Jquery
$(document).ready(function() {
$('#selecctall').mouseup(function(event) { //on click
if(document.activeElement.tagName ==='BUTTON') { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
Simpler and more efficient way

Related

Multiple checkbox with button

How to select topics the user likes before it proceeds using checkboxes. I want the next button to be enabled only after a checkbox is selected.
HTML
<input type="submit" value="Next" id="next" disabled="disabled">
<ul>
<li>
<input class="checkbox" type="checkbox" id="chkPlant1" unchecked="checked"/>
<label for="chkPlant1"><img src="img/plant1.jpg" /></label>
</li>
<li>
<input class="checkbox" type="checkbox" id="chkPlant2" />
<label for="chkPlant2"><img src="img/plant2.jpg" /></label>
</li>
<li>
<input class="checkbox" type="checkbox" id="chkPlant3" />
<label for="chkPlant3"><img src="img/plant3.png" /></label>
</li>
<li>
<input class="checkbox" type="checkbox" id="chkPlant4" />
<label for="chkPlant4"><img src="img/plant4.jpg" /></label>
</li>
</ul>
<script type="text/javascript">
$(function () {
$("#chkPlant1").change(function () {
if($('#chkPlant1').is(':checked')) {
$("#next").prop("disabled", false);
}
else {
$("#next").prop("disabled", true);
}
});
});
</script>
Target any input with class input.checkbox and not just the first one and check inside if any of them is checked, this will make sure at least one is picked.
$("input.checkbox").change(function() {
if ($("input.checkbox").is(':checked')) {
$(function() {
$("input.checkbox").change(function() {
if ($("input.checkbox").is(':checked')) {
$("#next").prop("disabled", false);
} else {
$("#next").prop("disabled", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="submit" value="Next" id="next" disabled="disabled">
<ul>
<li>
<input class="checkbox" type="checkbox" id="chkPlant1" unchecked="checked" />
<label for="chkPlant1"><img src="img/plant1.jpg" /></label>
</li>
<li>
<input class="checkbox" type="checkbox" id="chkPlant2" />
<label for="chkPlant2"><img src="img/plant2.jpg" /></label>
</li>
<li>
<input class="checkbox" type="checkbox" id="chkPlant3" />
<label for="chkPlant3"><img src="img/plant3.png" /></label>
</li>
<li>
<input class="checkbox" type="checkbox" id="chkPlant4" />
<label for="chkPlant4"><img src="img/plant4.jpg" /></label>
</li>
</ul>
Use :checked pseudo-selector with length property as it shown below:
$(function() {
function updateView() {
// count of all checked inputs with class .checkbox
if ($("input.checkbox:checked").length > 0) {
$("#next").prop("disabled", false);
} else {
$("#next").prop("disabled", true);
}
}
// match all inputs with class .checkbox
$("input.checkbox").change(function(event) {
updateView();
});
// initialize
updateView();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="submit" value="Next" id="next">
<ul>
<li><input class="checkbox" type="checkbox" id="chkPlant1" /></li>
<li><input class="checkbox" type="checkbox" id="chkPlant2" /></li>
<li><input class="checkbox" type="checkbox" id="chkPlant3" /></li>
<li><input class="checkbox" type="checkbox" id="chkPlant4" /></li>
</ul>
I hope this could help, if you don't want to use the class
<script type="text/javascript">
$(function () {
$("#chkPlant1").change(function () {
if($('#chkPlant1').is(':checked')) {
$("#next").prop("disabled", false);
}
else {
$("#next").prop("disabled", true);
}
});
$("#chkPlant2").change(function () {
if($('#chkPlant2').is(':checked')) {
$("#next").prop("disabled", false);
}
else {
$("#next").prop("disabled", true);
}
});
$...
});
</script>

Issue changing value into dynamic parent and child checkboxes

Here is the live demo updated
Problem: Trying to change value according dynamic checkboxes:
When I do click on the parent checkbox should change value="1" on childs
<input type="checkbox" class="parentCheckBox" value="1">
<input type="checkbox" class="childCheckBox" value="1">
<input type="checkbox" class="childCheckBox" value="1">
When I uncheck the parent should be value="0" on childs
<input type="checkbox" class="parentCheckBox" value="0">
<input type="checkbox" class="childCheckBox" value="0">
<input type="checkbox" class="childCheckBox" value="0">
Code:
<script src="https://code.jquery.com/jquery-2.2.1.js"></script>
<div>
<input type="checkbox" class="parentCheckBox" /> Parent 1 <a onclick="document.getElementById('div_1').style.display='';return false;"><img src="https://cdn0.iconfinder.com/data/icons/ie_Bright/512/plus_add_green.png" height="20" width="20"></a> <a onclick="document.getElementById('div_1').style.display='none';return false;"><img src="https://cdn0.iconfinder.com/data/icons/ie_Bright/512/minus_remove_green.png" height="20" width="20"></a><br />
<div id="div_1" style="display:none;">
<ul>
<li><input type="checkbox" class="childCheckBox" />Child 1-1 </li>
<li><input type="checkbox" class="childCheckBox" />Child 1-2 </li>
<li><input type="checkbox" class="childCheckBox" />Child 1-3 </li>
</ul>
</div>
</div>
<div>
<input type="checkbox" class="parentCheckBox" /> Parent 2 <a onclick="document.getElementById('div_2').style.display='';return false;"><img src="https://cdn0.iconfinder.com/data/icons/ie_Bright/512/plus_add_green.png" height="20" width="20"></a> <a onclick="document.getElementById('div_2').style.display='none';return false;"><img src="https://cdn0.iconfinder.com/data/icons/ie_Bright/512/minus_remove_green.png" height="20" width="20"></a><br />
<div id="div_2" style="display:none;">
<ul>
<li><input type="checkbox" class="childCheckBox" />Child 2-1 </li>
<li><input type="checkbox" class="childCheckBox" />Child 2-2 </li>
<li><input type="checkbox" class="childCheckBox" />Child 2-3 </li>
</ul>
</div>
</div>
Script:
$(document).on('change', '.parentCheckBox', function() {
var that = $(this);
that.closest('div').find('.childCheckBox').prop('checked', that.is(':checked'));
$(this).val($(this).prop('checked')?1:0);
});
$(document).on('change', '.childCheckBox', function() {
var that = $(this);
var par = that.closest('ul');
var c = par.find('.childCheckBox').filter(':checked').length;
var parChk = par.closest('div').parent().find('.parentCheckBox');
var checked = c > 0;
$(this).val($(this).prop('checked')?1:0);
parChk.prop('checked', checked);
console.log(checked);
});
Adding the logic to update children value.
$(document).on('change', '.parentCheckBox', function() {
var that = $(this);
that.closest('div').find('.childCheckBox').prop('checked', that.is(':checked')).val(that.is(':checked')?1:0);
});
$(document).on('change', '.childCheckBox', function() {
var that = $(this);
$(this).val($(this).prop('checked') ? 1 : 0);
var par = that.closest('ul');
var c = par.find('.childCheckBox').filter(':checked').length;
var parChk = par.closest('div').parent().find('.parentCheckBox');
var checked = c > 0;
parChk.prop('checked', checked);
console.log(checked);
});
I am not 100% sure what you are trying to accomplish, but here are two pretty straight forward examples of what I think you are trying to do.
This is usually not how you use checkboxes. They have one value set, by default all checkboxes has the value 'on'. But you can use 1 or any other value as well. There is no need to change their value. If the checkbox is checked decides if it will post that value or not, if this was a form.
But, just to demonstrate how you can change the values based on change, I have two examples.
Simplified example:
HTML:
<ul>
<li><input type="checkbox" class="childCheckBox">Child 1-1 </li>
<li><input type="checkbox" class="childCheckBox">Child 1-2 </li>
<li><input type="checkbox" class="childCheckBox">Child 1-3 </li>
</ul>
JavaScript:
// When checkbox is changed
$('.childCheckBox').on('change', function(e){
// Check if its checked
if($(this).prop('checked')) {
// If checked, set value to 1
$(this).val(1);
} else {
// If not checked, set value to 0
$(this).val(0);
}
// Log value of changed checkbox
console.log($(this).val());
});
https://jsbin.com/mewefegopi/edit?html,js,output
Longer example with parents:
HTML:
<div class="wrapper">
<input type="checkbox" class="parentCheckBox" /> Parent 1
<ul>
<li><input type="checkbox" class="childCheckBox">Child 1-1 </li>
<li><input type="checkbox" class="childCheckBox">Child 1-2 </li>
<li><input type="checkbox" class="childCheckBox">Child 1-3 </li>
</ul>
</div>
<div class="wrapper">
<input type="checkbox" class="parentCheckBox" /> Parent 2
<ul>
<li><input type="checkbox" class="childCheckBox">Child 2-1 </li>
<li><input type="checkbox" class="childCheckBox">Child 2-2 </li>
<li><input type="checkbox" class="childCheckBox">Child 2-3 </li>
</ul>
</div>
JavaScript:
// When parent checkbox is changed
$('.parentCheckBox').on('change', function(e){
var self = this;
// Get all child checkboxes
var childs = $(this).closest('.wrapper').find('.childCheckBox');
// Go though all childs
$(childs).each(function(i, e){
// If parent is checked set child value to 1
if($(self).prop('checked')) {
$(this).val(1);
} else { // ...else set child value to 0
$(this).val(0);
}
});
});
https://jsbin.com/qisizudupa/edit?html,js,output
$(document).on('click', '.childCheckBox', function(e) {
var childCheckBoxInput = $(e.target);
if (childCheckBoxInput.is(':checked')) {
chilCheckBoxInput.val(1);
} else {
childCheckBoxInput.val(0);
}
});

Exclude disabled checkboxes when using Select All

I have checkboxes with labels in table. I have added one checkbox outside the table "Select All" with id "chkbox". Now the below code is working fine. It is
Selecting and Deselecting all the checkboxes in the table. Now there are some pages where some checkboxes are disabled due to business logic. I want these checkboxes should not be affected.
<script type="text/javascript">
var s = jQuery.noConflict();
s(document).ready(function() {
s('#chkbox').change(function() {
var all = s('table').find('input[type="checkbox"]');
if (this.checked) {
all.prop('checked', true);
} else {
all.prop('checked', false);
}
});
});
</script>
Use :not() with :disabled selector.
var all = $('table').find('input[type="checkbox"]:not(:disabled)');
^^^^^^^^^^^^^^^^
This will not select the disabled checkboxes
$('#selectAll').change(function() {
$(':checkbox:not(:disabled)').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" id="selectAll" />Select All
<ul>
<li>
<input type="checkbox" disabled />
</li>
<li>
<input type="checkbox" />Not disabled</li>
<li>
<input type="checkbox" />Not disabled</li>
<li>
<input type="checkbox" disabled />
</li>
<li>
<input type="checkbox" />Not disabled</li>
</ul>
You can also use :enabled selector.
$('table').find('input[type="checkbox"]:enabled')
$('#selectAll').change(function() {
$(':checkbox:enabled').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" id="selectAll" /> Select All
<ul>
<li>
<input type="checkbox" disabled />
</li>
<li>
<input type="checkbox" />Not disabled</li>
<li>
<input type="checkbox" />Not disabled</li>
<li>
<input type="checkbox" disabled />
</li>
<li>
<input type="checkbox" />Not disabled</li>
</ul>
Note that: :enabled == :not(:disabled)

jquery check and uncheck all with action

I have more checkbox input that call function "boxclick" when the user click on this:
<input id="1box" type="checkbox" name="selected[]" onclick="boxclick(this,'1')">
<input id="2box" type="checkbox" name="selected[]" onclick="boxclick(this,'2')">
<input id="3box" type="checkbox" name="selected[]" onclick="boxclick(this,'3')">
<input id="4box" type="checkbox" name="selected[]" onclick="boxclick(this,'4')">
For check/uncheck all i use simple jquery script:
<input type="checkbox" onclick="$('input[name*=\'selected\']').attr('checked', this.checked);" checked="checked">
My problem is when i check/uncheck all the function "boxclick" not run.
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}
I think you can do:
HTML
<input id="1box" type="checkbox" name="selected[]">
<input id="2box" type="checkbox" name="selected[]">
<input id="3box" type="checkbox" name="selected[]">
<input id="4box" type="checkbox" name="selected[]">
jQuery
If you want to check/uncheck all checkbox:
var checkboxes = $('input[type=checkbox][name^=selected]');
checkboxes.on('click', function() {
checkboxes.prop('checked', this.checked);
});
If you want to make select any one at a time:
var checkboxes = $('input[type=checkbox][name^=selected]');
checkboxes.on('click', function() {
checkboxes.prop('checked', false);
this.checked = !this.checked;
});​
DEMO
Setting attribute of checkboxes to checked does not automatically fake a click event for you! Because you put those boxclick function calls within some "onclick" handlers, you must trigger a fake click event in order for your javascript to think that it clicked all the boxes. To trigger fake click event use $('#whatever').trigger('click'), for instance:
$('input[name*=\'selected\']').trigger('click');
If you want check/uncheck all functionality, you must say "ok, master checkbox, please listen for whenever I am checked or unchecked. When that happens, please set checked attribute of my slave boxes (your other boxes on the page) to match the master's current checked attribute." Like this:
function checkAllorUncheckAll(event){
var chiefCheckbx = event.currentTarget;
var myBoxes = $('input[name*=\'selected\']');
myBoxes.prop( "checked", $(chiefCheckbx).prop("checked") ).trigger('click');
}
$('#masterCheckBox').on('change',checkAllorUncheckAll);
I guess
$('input[name*=\'selected\']').attr('checked',
this.checked).trigger('click');
should do the trick here
Demo
http://jsfiddle.net/H37cb/
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});
});
</script>
<div id="wrapper">
<li style="margin-top: 20px">
<input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
<ul>
<li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
<li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
<li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
<li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
</ul>
</li>
</ul>
<ul>
<li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
<li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
<li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
</ul>
</li>
</ul>
</li>
</div>

Selecting Parent Checkboxes

I have a page that has a tree structure that has no limit to the number of levels it has. Each level has a tick box I need to be able to allow users to tick which levels they are interested in. If a user clicks on a level then all of the parent levels for that child need to be selected. Also if the parent check box is unticked then all child levels should be unticked.
I tried writing the code below which kind of works however if I click the child it will tick the parent and grandparent but leave the child unselected. I am also unable to unselect items as every-time I select a box it always selects it again.
I keep trying to make changes to the code and have ideas but I think I am going down the wrong direction and wanted to know if there are better solutions available for what I am trying to achieve. Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Check Box</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script language="javascript">
$(document).ready(function () {
$(".test").click(function (event) {
event.preventDefault();
});
});
function set_checked(id, checked) {
$("#ID_" + id).attr("checked", checked)
alert(id);
}
function CheckMe(id) {
var IDS = id.replace("ID_", "");
var IDS = IDS.split('_');
for (i = 0; i < IDS.length; i++) {
set_checked(IDS[i], true);
}
}
</script>
</head>
<body>
<div>
<form>
<p>
<input name="ID" type="checkbox" id="ID_123" value="123" onClick="CheckMe('ID_123')" class="test">Grandparent
<br>
<input name="ID" type="checkbox" id="ID_124" value="124" onClick="CheckMe('ID_123_124')"class="test">Parent
<br>
<input name="ID" type="checkbox" id="ID_125" value="125" onClick="CheckMe('ID_123_124_125')"class="test">Child
</p>
<p>
<input type="submit" name="button" id="button" value="Submit">
</p>
</form>
</div>
</body>
</html>
I used jQuery PreventDefault to stop the default actions of the checkbox. I would be most grateful for any direction with this.
Edit:
Here are the options within an unordered list. My example above was misleading as it only had three options as I was trying to test clicking the bottom option and having the parent options clicked without considering that there would be multiple trees.
<form action="" method="get" id="test">
<ul>
<li>
<input type="checkbox" name="ID" value="1">
<label>Level 1</label>
<ul>
<li><input type="checkbox" name="ID" value="2"><label>Level 1.1</label>
<ul>
<li><input type="checkbox" name="ID" value="3"><label>Level 1.1.1</label>
</ul>
</ul>
<ul>
<li><input type="checkbox" name="ID" value="4"><label>Level 1.2</label>
<ul>
<li><input type="checkbox" name="ID" value="5"><label>Level 1.2.1</label>
<li><input type="checkbox" name="ID" value="6"><label>Level 1.2.2</label>
<li><input type="checkbox" name="ID" value="7"><label>Level 1.2.3</label>
<ul>
<li><input type="checkbox" name="ID" value="8"><label>Level 1.2.3.1</label>
<li><input type="checkbox" name="ID" value="9"><label>Level 1.2.3.2</label>
</ul>
<li><input type="checkbox" name="ID" value="10"><label>Level 1.2.4</label>
<li><input type="checkbox" name="ID" value="11"><label>Level 1.2.5</label>
<li><input type="checkbox" name="ID" value="12"><label>Level 1.2.6</label>
</ul>
</ul>
<li><input type="checkbox" name="ID" value="13"><label>Level 2</label>
<ul>
<li><input type="checkbox" name="ID" value="14"><label>Level 2.1</label>
<ul>
<li><input type="checkbox" name="ID" value="15"><label>Level 2.1.1</label>
</ul>
<li><input type="checkbox" name="ID" value="16"><label>Level 2.2</label>
<ul>
<li><input type="checkbox" name="ID" value="16"><label>Level 2.2.1</label>
<li><input type="checkbox" name="ID" value="17"><label>Level 2.2.2</label>
<li><input type="checkbox" name="ID" value="18"><label>Level 2.2.3</label>
<ul>
<li><input type="checkbox" name="ID" value="19"><label>Level 2.2.3.1</label>
<li><input type="checkbox" name="ID" value="20"><label>Level 2.2.3.2</label>
</ul>
<li><input type="checkbox" name="ID" value="21"><label>Level 2.2.4</label>
<li><input type="checkbox" name="ID" value="22"><label>Level 2.2.5</label>
<li><input type="checkbox" name="ID" value="23"><label>Level 2.2.6</label>
</ul>
</ul>
</ul>
<input name="Submit" type="submit" id="Button" value="Submit">
</form>
There are plugins that already provide this functionality.
Try this, as it does exactly what you are looking for.
http://code.google.com/p/checkboxtree/
demo:
http://checkboxtree.googlecode.com/svn/tags/checkboxtree-0.5.2/index.html
Try this code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Check Box</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
<script language="javascript">
$(document).ready(function () {
$(".test").on('click',function () {
var clicked = $(this);
var hermanos = clicked.siblings(".test");
if(clicked.attr("checked")=="checked")
$.each(hermanos, function(index,object){
if($(object).val() < clicked.val())
$(object).attr("checked", "checked");
});
else
$.each(hermanos, function(index,object){
if($(object).val() > clicked.val())
$(object).removeAttr("checked");
});
});
});
</script>
</head>
<body>
<div>
<form>
<p>
<input name="ID" type="checkbox" value="123" class="test">Grandparent
<br>
<input name="ID" type="checkbox" value="124" class="test">Parent
<br>
<input name="ID" type="checkbox" value="125" class="test">Child
</p>
<p>
<input type="submit" name="button" id="button" value="Submit">
</p>
</form>
</div>
</body>
Not sure what you mean with "levels", are the checkboxes nested inside other elements, or are they as in your example, just siblings ?
If the example HTML is correct, remove all your inline JS, and just do this :
$(".test").on('change', function() {
var i = $(this).index(),
c = $(this).is(':checked');
$(".test").filter(function() { return $(this).index() < i; }).prop('checked', c);
});
FIDDLE

Categories

Resources