document.querySelectorAll('') How does it works? - javascript

I would like some tips about JS querySelectorAll('').
I need to count some checkboxes to establish a maximun of selection. The problem is I dont want to count them all the checked, just the ones with the 'name=homeCheck' and in the way I'm using querySelectorAll it's not working fine:
function insertDeleteNews(data) {
if (checked == true && document.querySelectorAll('input[type="checkbox"]:checked').length > 6){
...}
}
<td><input type="checkbox" name="homeCheck" id="homeCheck_<?=$row['id']."_".$row['id_azienda']?>" value="<?=$row['id']."_".$row['id_azienda']?>" <?= $rowHome ?"checked":""?> <?= !$rowNews ?"disabled":""?> onclick="insertDeleteNews(this.value)"></td>

You can query for the name-property instead of the type-property:
input[name="name1"]:checked
General example:
let button = document.getElementById('button');
button.addEventListener('click', function(event) {
event.preventDefault();
let count = document.querySelectorAll('input[name="name1"]:checked').length;
console.log(count);
});
<input type="checkbox" name="name1"> Name1 (1)<br>
<input type="checkbox" name="name2"> Name2 (1)<br>
<input type="checkbox" name="name1"> Name1 (2)<br>
<input type="checkbox" name="name2"> Name2 (2)<br>
<input type="checkbox" name="name1"> Name1 (3)<br>
<button id="button">Count Name1</button>
Example - limit to max 3 checked:
let checkboxes = document.querySelectorAll('input[name="homeCheck"]');
for (let checkbox of checkboxes) {
checkbox.addEventListener('click', checkboxLimitTo3Checked);
}
function checkboxLimitTo3Checked(event) {
let checked = document.querySelectorAll('input[name="homeCheck"]:checked').length;
if (checked > 3) {
event.preventDefault();
}
}
<input type="checkbox" name="homeCheck"> homeCheck 1<br>
<input type="checkbox" name="homeCheck"> homeCheck 2<br>
<input type="checkbox" name="homeCheck"> homeCheck 3<br>
<input type="checkbox" name="homeCheck"> homeCheck 4<br>
<input type="checkbox" name="homeCheck"> homeCheck 5<br>

You can replace your function by
function insertDeleteNews(data) {
if (document.querySelectorAll('input[name="homeCheck"]:checked').length > 6){
...}
}
This will find all the checked inputs with name = "homeCheck"

Related

Condition: input:checked with the same class

I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.
The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

get all elements by class name of text boxes in javascript

I have a few text boxes on my javascript page with the class of textID. So if I were to do
function UpdateTotals() {
getText = document.getElementsByClassName('textID').value;
}
All of the values will be numbers, so how do I add all of the values in this class together? Example: there are 4 text boxes, each one has the number 2 in it. I want to get 8 by adding them all together (but only the text boxes that are in that class).
One example could be using Array.prototype.reduce()
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.textContent.trim()), 0);
console.log(total); // 8
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
For INPUT elements:
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.value), 0);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Using NodeList.forEach()
const textID = document.querySelectorAll('.textID');
let total = 0;
textID.forEach(el => total += +el.value);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Try this code:
HTML code:
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<br><br>
Total : <input type="text" name="total" id="total"/>
Sum
JS code:
window.sumInputs = function() {
var inputs = document.getElementsByClassName('textID'),
result = document.getElementById('total'),
checkboxes = document.querySelectorAll(`input[name="qty"]:checked`),
sum = 0;
for(var i=0; i<checkboxes.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
Try it in jsfiddle : https://jsfiddle.net/u62tyj45/

How to get my results to add up correctly in javascript

I have a small script that checks for selected boxes and ads them up.
Some boxes are worth two some are worth one.
I can get them to add up, but only if I select one of two pointers first or vice versa.
Html
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">Some blah blah text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="two">Text</label>
</div>
<div class="checkbox pmmargin">
<label><input type="checkbox" value="" class="one">text</label>
</div>
The Javascript
$(".two").change(function() {
var classes = $("input[type='checkbox'].two:checked").map(function() {
return this.className;
}).get().length * 2;
document.getElementById("program_management2").innerHTML = " Score:" + " " + Math.floor(classes) ;
$(".one").change(function() {
var classes2 = $("input[type='checkbox'].one:checked").map(function() {
return this.className;
}).get().length;
document.getElementById("program_management").innerHTML = " Score:" + " " + Math.floor(classes2 + classes) ;
});
});
If you only want to add the value of each checked checkbox, you should use the value attribute.
Since the value is a string, you have to parse it to an integer to use it in an addition.
$("input[type='checkbox']").click(function(){
var result = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1">This box value is 1<br>
<input type="checkbox" value="2">This box value is 2<br>
<input type="checkbox" value="5">This box value is 5<br>
<br>
<br>
The checked total is: <span id="total">0</span>
EDIT
I added a "checked class" count.
$("input[type='checkbox']").click(function(){
var result = 0;
var classOne = 0;
var classTwo = 0;
$("input[type='checkbox']:checked").each(function(){
result += parseInt($(this).val());
if( $(this).hasClass("one") ){
classOne++;
}
if( $(this).hasClass("two") ){
classTwo++;
}
$("#totalOne").html(classOne);
$("#totalTwo").html(classTwo);
});
$("#total").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="1" class="one">This box value is 1<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<input type="checkbox" value="2" class="two">This box value is 2<br>
<br>
<br>
The checked total value is: <span id="total">0</span><br>
Class "one" checked total : <span id="totalOne">0</span><br>
Class "two" checked total : <span id="totalTwo">0</span><br>

Getting multiple checked checkbox labels into an array

I am hoping to get all the checked checkboxes from my form into an array.
Here is what I did.
$("div.category-panel input:checked").next ('label').text(); perfectly gets all the checked checkboxes but it just shows them together as one text. As an example, checkbox1, checkbox2 and checkbox3 (if checked) would show as checkbox1checkbox2checkbox3.
I was hoping to get these different checkboxes in an array so that I can use them.
$('.submit').on("click", function(e) {
//got all checked checkboxes into 'children'.
children = $("div.category-panel input:checked").next ('label').text();
//Put in array.
var array = [];
var i = 0;
$.each(children, function(key, value){
array.push($(this).text());
});
//Show the array.
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
});
HTML, just in case is:-
<div class="category-panel">
<input type="checkbox" name="name_service2" id="tid-46" value="46" checked="checked"> <label class="option" for="edit-tid-46">CheckBox1</label>
<input type="checkbox" name="name_service3" id="tid-47" value="47" checked="checked"> <label class="option" for="edit-tid-47">CheckBox2</label>
<input type="checkbox" name="name_service4" id="tid-44" value="44" checked="checked"> <label class="option" for="edit-tid-44">CheckBox3</label>
<input type="checkbox" name="name_service5" id="tid-48" value="48" checked="checked"> <label class="option" for="edit-tid-48">CheckBox4</label>
</div>
You can use .map() like
$('.submit').on("click", function (e) {
//got all checked checkboxes into 'children'.
var array = $("div.category-panel input:checked").next('label').map(function(){
return $(this).text();
}).get();
//Show the array.
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
});
$('.submit').on("click", function(e) {
//got all checked checkboxes into 'children'.
var array = $("div.category-panel input:checked").next('label').map(function() {
return $(this).text();
}).get();
//Show the array.
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="category-panel">
<input type="checkbox" name="name_service2" id="tid-46" value="46" checked="checked" />
<label class="option" for="edit-tid-46">CheckBox1</label>
<input type="checkbox" name="name_service3" id="tid-47" value="47" checked="checked" />
<label class="option" for="edit-tid-47">CheckBox2</label>
<input type="checkbox" name="name_service4" id="tid-44" value="44" checked="checked" />
<label class="option" for="edit-tid-44">CheckBox3</label>
<input type="checkbox" name="name_service5" id="tid-48" value="48" checked="checked" />
<label class="option" for="edit-tid-48">CheckBox4</label>
</div>
<button class="submit">submit</button>
In your case children is a string, which contains the concatenated text of all label's which are next siblings of checked checkboxes
you need to use .map() function to get the all labels text as object. then use .get() to get them in array:
$("div.category-panel input:checked").next('label').map(function(){
return $(this).text();
}).get();// ["checkbox1","checkbox2" ,"checkbox3"]
If you want them as comma separated values, use .join() after .get()
$("div.category-panel input:checked").next('label').map(function(){
return $(this).text();
}).get().join();// "checkbox1, checkbox2 ,checkbox3"
<input type="checkbox" name="name_service2" id="tid-46" value="46" checked="checked" /> <label class="option" for="edit-tid-46">A Value</label>
<input type="checkbox" name="name_service3" id="tid-47" value="47" checked="checked" /> <label class="option" for="edit-tid-47">A Value</label>
<input type="checkbox" name="name_service4" id="tid-44" value="44" checked="checked" /> <label class="option" for="edit-tid-44">A Value</label>
<input type="checkbox" name="name_service5" id="tid-48" value="48" checked="checked" /> <label class="option" for="edit-tid-48">A Value</label>
$('.submit').on("click", function(e) {
//got all checked checkboxes into 'children'.
children = $("div.category-panel input:checked").next ('label');
//Put in array.
var array = [];
$.each(children, function(){
array.push($(this).text());
});
//Show the array.
$(array).each(function(){
console.log(this.toString());
});
});
http://jsfiddle.net/7ryhv07e/1/

Check All checkbox should be unchecked

function toggle(source) {
checkboxes = document.getElementsByName('options[]');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" onClick="toggle(this)" />
<label for="checkbox-1-6"></label>All
<br>
<input type="submit" name="formSubmit" value="Unsubscribe" />
</form>
When I check the All checkbox, of course, it will mark all the checkboxes, but once I uncheck one checkbox, the All checkbox is still checked. This should be unchecked. How should I do that using JS?
You will need to add onchange event handlers to every checkbox and check inside if the "All" checkbox should be checked (all checkboxes are selected) or unchecked (at least one is deselected). For example like this:
var checkboxes = [].slice.call(document.getElementsByName('options[]')),
allCheckbox = document.querySelector('input[value="All"]');
checkboxes.forEach(function(checkbox) {
checkbox.onchange = function() {
if (!this.checked) {
allCheckbox.checked = false;
}
else {
var checked = checkboxes.filter(function(check) {
return check.checked;
});
if (checked.length === checkboxes.length) {
allCheckbox.checked = true;
}
}
};
});
function toggle(source) {
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" onClick="toggle(this)" />
<label for="checkbox-1-6"></label>All
</form>
Note that I converted checkboxes collection to array with [].slice.call in order to use convenient array methods. Simple for loops can be used instead.
I'd suggest the following:
function toggle() {
// getting a reference to all the 'name="option[]" elements:
var options = document.getElementsByName('options[]'),
// a reference to the 'all' checkbox:
all = document.getElementById('checkbox-1-6');
// if the changed checkbox is the 'all':
if (this === all) {
// we iterate over all the options checkboxes (using
// Array.prototype.forEach()):
Array.prototype.forEach.call(options, function(checkbox) {
// and we set their checked property to the checked property
// state of the 'all' checkbox:
checkbox.checked = all.checked;
});
} else {
// otherwise we set the 'all' checkbox to the state of
// the Boolean returned by Array.prototype.every(),
// which returns true if all checkboxes evaluate to
// the condition within the function, otherwise false:
all.checked = Array.prototype.every.call(options, function(checkbox) {
return checkbox.checked;
});
}
}
// getting a NodeList of all the elements of 'class="unsubscribe-checkbox"':
var options = document.querySelectorAll('.unsubscribe-checkbox');
// iterating over them, again with Array.prototype.forEach()
// and assigning a change event-listener, which will execute the
// name function:
Array.prototype.forEach.call(options, function(opt) {
opt.addEventListener('change', toggle);
});
function toggle() {
var options = document.getElementsByName('options[]'),
all = document.getElementById('checkbox-1-6');
if (this === all) {
Array.prototype.forEach.call(options, function(checkbox) {
checkbox.checked = all.checked;
});
} else {
all.checked = Array.prototype.every.call(options, function(checkbox) {
return checkbox.checked;
});
}
}
var options = document.querySelectorAll('.unsubscribe-checkbox');
Array.prototype.forEach.call(options, function(opt) {
opt.addEventListener('change', toggle);
});
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" />
<label for="checkbox-1-6"></label>All
<br>
<input type="submit" name="formSubmit" value="Unsubscribe" />
</form>
You may notice that I've removed the onClick attribute from the 'all' checkbox, in preference of unobtrusive JavaScript, where the event-handlers are assigned via the JavaScript itself (which ordinarily makes for more easily-maintained code, as the arguments to be passed to a given function are assigned in the code itself, rather than having to be separately updated in the HTML).
References:
Array.prototype.every().
Array.prototype.forEach().
document.getElementsByName().
document.getElementById().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().

Categories