About updating values in multiple check boxes - javascript

I have created multiple checkboxes using a script in an HTML file.
I want to updates the checkboxes using name based on a condition like the below.
Checkboxes[I].checked = true;
But it's throwing an error.
Can you please suggest a way to solve this issue out.

for this purpose I will try to answer you, I have two options, by class or tag name, may if you want to use Jquery its also nice. I prepare an example for you, I hope that this one helps you, greetings
function toggleA() {
var elm = document.getElementsByClassName('chx');
for(var i = 0; i < elm.length; i++) {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
function toggleB() {
var elm = $(".chx").prop("checked")
$(".chx").prop( "checked", !elm );
}
function toggleC() {
var elm = document.getElementsByTagName('input');
for(var i = 0; i < elm.length; i++) {
if(elm[i].type.toLowerCase() == 'checkbox') {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" onclick="toggleA()">Toggle A</button>
<button id="btn" onclick="toggleB()">Toggle B</button>
<button id="btn" onclick="toggleC()">Toggle C</button>
<br><br>
<label>
<input id="check-a" class = "chx" onchange="alert('Changed A!')" type="checkbox"> A
</label>
<br><br>
<label>
<input id="check-b" class = "chx" onchange="alert('Changed B!')" type="checkbox"> B
</label>
<br><br>
<label>
<input id="check-jq" class = "chx" onchange="alert('Changed JQ!')" type="checkbox"> JQ
</label>
<br><br>
<label>
<input id="check-c" class = "chx" onchange="alert('Changed C!')" type="checkbox"> C
</label>

Related

How to search different digits in numbers

I have a function which split the input value on space and I looped through to search them in a number but only the last value is shown (checked) not the other before it .
One solution can be by removing else that way it worked fine but this way when changing the value the checked number remain intact(last searched result are also shown).
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var reader = document.getElementsByClassName("checkbox_inputs")
for (let i = 0; i < reader.length; i++) {
var readerText = reader[i].value
var readerText1 = readerText.trim()
var reed = document.getElementById("allNumbers").value;
var reed1 = reed.trim()
var myDiffValues = reed1.split(" ");
document.getElementById("demo").innerHTML = myDiffValues
if (reed != '') {
for (var item of myDiffValues) {
if (readerText1.indexOf(item) > -1) {
reader[i].checked = true;
} else {
reader[i].checked = false;
}
}
} else {
reader[i].checked = false;
}
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
One strange behavior it is showing is when lot of space is entered in the input all checkboxes get checked
You can make it much more easily :)
Explanation
First of all you read your inputs (checkbox_inputs).
Then you
read just once the numbers (allNumbers) and you can trim and split
in one line.
Last step: for each one of your checkboxes you set the checked value if the allNumbers list includes the expected value. false otherwise.
Working Example
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var inputs = document.getElementsByClassName("checkbox_inputs");
var allNumbers = document.getElementById("allNumbers").value.trim().split(" ");
document.getElementById("demo").innerHTML = allNumbers
for (let i = 0; i < inputs.length; i++) {
inputs[i].checked = allNumbers.includes(inputs[i].value);
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>

How to detect which element contains all other X elements

(Hope this question hasn't been asked yet : I didn't find it via a keyword search)
I'd like to detect, using jQuery, which element (div, span, anything) contains all the other XKindOfElement.
Meaning, for example, if I have multiple checkboxes in my screen, I want to know which div contains all those checkboxes.
<div id="block1">
<div id="underblock1">
<input type="checkbox" name="thing[]" value="1" />
<div id="underunderblock1">
<input type="checkbox" name="thing[]" value="2" />
</div>
</div>
<div id="underblock2">
<input type="checkbox" name="thing[]" value="3" />
</div>
</div>
In this example, it will return the div#block1 because only it contains all the input[type="checkbox"] of the page.
Hope you'll understand and could help me !
UPDATE
Thinking of something... What do you think about this process :
Check if our element exists in the page
If so, count how many of this element exists and save it (let's say count)
Check if the parent of the first element find contains all the count elements
If not, check if the parent of the parent contains all the count elements,
etc
When the checked parent does contain all the count elements: it is our "smallest global parent" !
Would it be ok or too slow, too "expansive"... ?
I'm not very familiar with all the jQuery helper methods, but this approach might work for you:
Collect all the elements you want to be included
Collect their parents arrays and reverse them: all these arrays now start with: html > body and continue all the way to the actual element
loop through a parent array and check if the other parent arrays have the same element at the current index
the first element that doesn't match marks the index of the last shared parent
Note: you might want to refactor the code a bit to make sure you don't run into any errors for edge cases.
var required = $("input[type=checkbox]");
var getClosestParent = function(elements) {
var maxLength = 0;
var allParents = [];
elements.each(function(i, el) {
var parents = $(el).parents().toArray().reverse();
maxLength = Math.max(maxLength, parents.length);
allParents.push(parents);
});
var ref = allParents[0];
var others = allParents.slice(1);
for (var i = 0; i < maxLength; i += 1) {
for (var j = 0; j < others.length; j += 1) {
if (ref[i] !== others[j][i]) {
return ref[i - 1];
}
}
}
return null;
}
console.log(getClosestParent(required).id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block1">
<div id="underblock1">
<input type="checkbox" name="thing[]" value="1" />
<div id="underunderblock1">
<input type="checkbox" name="thing[]" value="2" />
</div>
</div>
<div id="underblock2">
<input type="checkbox" name="thing[]" value="3" />
</div>
</div>
Get an array of arrays for each of the parents, then loop over them until you find a miss-match:-
var parents = new Array();
var minDepth = (Math.pow(2, 53) - 1);
$('[type=checkbox]').each(function(i, e) {
parents.push($(e).parents().get().reverse());
if (minDepth > parents[i].length)
minDepth = parents[i].length;
});
var topParent, testParent;
finished:
for (var i = 0; i < minDepth; i++) {
testParent = parents[0][i];
for (var j = 0; j < parents.length; j++) {
if (parents[j][i] != testParent)
break finished;
}
topParent = parents[0][i];
}
console.log(topParent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block1">
<div id="underblock1">
<input type="checkbox" name="thing[]" value="1" />
<div id="underunderblock1">
<input type="checkbox" name="thing[]" value="2" />
</div>
</div>
<div id="underblock2">
<input type="checkbox" name="thing[]" value="3" />
</div>
</div>
Ok so, I'm answering to myself thx to you guys. I thought about #user3297291 said, however I still think starting from the element itself is faster than starting from html > body > etc.
So I make this, what do you think ?
var required = jQuery("input[type=checkbox]");
var getClosestGlobalParent = function(elements) {
var count = elements.length,
result = null;
if(count) {
if(count > 1) {
jQuery(elements[0]).parents().each(function(i, el) {
if(jQuery(this).find(elements).length == count) {
result = jQuery(this); // We also can return "this"
return false; // If the parent is found, we stop the .each loop
}
});
} else {
result = jQuery(elements[0]).parent(); // If there's only one element, his closest parent IS his .parent()
}
}
return result;
}
console.log(getClosestGlobalParent(required).attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="under_container">
<div id="block1">
<div id="underblock1">
<input type="checkbox" name="thing[]" value="1" /> Val1
<div id="underunderblock1">
<input type="checkbox" name="thing[]" value="2" /> Val2
</div>
</div>
<div id="underblock2">
<input type="checkbox" name="thing[]" value="3" /> Val3
<br /><input type="checkbox" name="thing[]" value="4" /> Val4
</div>
</div>
</div>
</div>
$.fn.sharedParents = function(){
if (this.length == 0)
return this;
var parents = $(this.get(0)).parents();
for (var i=0; i<parents.length; i++)
for (var j=1; j<this.length; j++)
if (!$.contains(parents[i], this[j]))
{
delete parents[i];
break;
}
return parents;
}
For given set of elements - get all the parents of the first element. Then for all the other elements check if given parents contain those elements. The result is a list of all parents containing all elements, and, as such, the deepest parent will be the first entry of that list.
https://jsfiddle.net/hwte8n3w/

Selecting radiobuttons using javascript.

I'm currently in the process of learning javascript. I want to create a dynamically quiz and now I want to check the value of my radiobuttons. This is my code:
HTML:
<div class="intro">
<h1>Welcome at my JavaScript Quiz</h1>
<br>
<span id="questions"></span>
<form name="radioAnswers">
<input type="radio" id="answer0" name="choice" value="a"><label for ="answer0" id="a0">Answer A</label>
<input type="radio" id="answer1" name="choice" value="b"><label for ="answer1" id="a1">Answer B</label>
<input type="radio" id="answer2" name="choice" value="c"><label for ="answer2" id="a2">Answer C</label>
<input type="radio" id="answer3" name="choice" value="c"><label for ="answer3" id="a3">Answer D</label>
</form>
<div class="buttons">
<button onclick="checkAnswers()">Submit answer</button>
</div>
And the checkAnswers function to check the answer. From what I understand the document.forms.radioAnswers.elements.choice will create an HTMLcollection. I want to iterate over this arraylike list and want to see which one is checked, and then put this into the answer variable. Like this:
function checkAnswers() {
var methods = document.forms.radioAnswers.elements.choice;
var answer;
for (var i = 0; i<methods.length; i++) {
if (methods[i].checked) {
answer = methods[i].value;
} else {
answer = "error"
}
} alert(answer);
}
When I run this it alerts "error" all the time. What am I missing?
You need to break the loop when you've found the answer, like this:
function checkAnswers() {
var methods = document.forms.radioAnswers.elements.choice;
var answer = "error";
for (var i = 0; i<methods.length; i++) {
if (methods[i].checked) {
answer = methods[i].value;
break;
}
}
alert(answer);
}
DEMO
Try this:
function checkAnswers() {
var answer="error";
if (document.getElementById('answer0').checked) {
answer = document.getElementById('answer0').value;
}
if (document.getElementById('answer1').checked) {
answer = document.getElementById('answer1').value;
}
if (document.getElementById('answer2').checked) {
answer = document.getElementById('answer2').value;
}
if (document.getElementById('answer3').checked) {
answer = document.getElementById('answer3').value;
}
alert(answer);
}
DEMO

Unchecking Boxes -- Javascript [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Is there a way to uncheck all boxes at once?
I have a 4x4 table of checkboxes and I set all their ID's to "cb". I want to have a button that clears all of them, so I tried doing something like below:
document.getElementById("cb").checked="false"
But on the screen, they still remain checked. Is this possible?
ID's are unique, so having multiple elements with the same ID wont solve the problem, it will only make your markup invalid. Use classes instead:
var boxes = document.getElementsByClassName("cb");
for (i=0; boxes.length<i; i++) {
boxes[i].checked = false;
}
You can use something like this:
function toggle(state) {
var cb = document.getElementsByName('cb');
for (var i = cb.length; i--;) {
cb[i].checked = typeof state != 'undefined' ? state : !cb[i].checked;
}
}
Usage:
toggle(false); // Uncheck all
toggle(true); // Check all
toggle(); // Toggle all
In this example you select checkboxes by the name attribute. You can also use class name and select inputs with document.getElementsByClassName or document.querySelectorAll methods.
Demo: http://jsfiddle.net/kCmqL/1/
Check this article Javascript Check and Uncheck All Checkboxes
Here is the code below:
Script
<script language="JavaScript">
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
HTML
<form name="myform" action="checkboxes.asp" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">Java<br>
<input type="checkbox" name="list" value="2">Javascript<br>
<input type="checkbox" name="list" value="3">Active Server Pages<br>
<input type="checkbox" name="list" value="4">HTML<br>
<input type="checkbox" name="list" value="5">SQL<br>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
<br>
</form>
Best Regards
Try
<script language="javascript">
function checkUnCheckAll(formname)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
</script>
More
You can also your same Name to all controls as below:
<input type="Checkbox" name="compare" id="compare" value="1" />
<input type="Checkbox" name="compare" id="Checkbox1" value="5" />
<input type="Checkbox" name="compare" id="Checkbox2" value="8" />
<input type="Checkbox" name="compare" id="Checkbox3" value="10" />
<input type="button" value="select all" onclick="javascript:checkAll()"/>
<input type="button" value="unckeck all" onclick="javascript: unCheckAll()"/>
<script type="text/javascript">
function checkAll()
{
var c = document.getElementsByName("compare");
for (var i = 0; i < c.length; i++) {
c[i].checked = true;
}
}
function unCheckAll() {
var c = document.getElementsByName("compare");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
}
</script>
While you already have an answer, I thought I'd post the following as an option also. Given the following minimal/demonstrative HTML mark-up:
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" checked />
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" checked />
<input type="checkbox" class="something" name="cb" checked />
The following JavaScript can be used to check, uncheck or toggle all checkboxes returned by the selector:
Object.prototype.check = function (newState) {
switch (newState.toLowerCase()) {
case 'toggle':
for (var i = 0, len = this.length; i<len; i++){
this[i].checked = !this[i].checked;
}
break;
case 'check':
for (var i = 0, len = this.length; i < len; i++) {
this[i].checked = true;
}
break;
case 'uncheck':
for (var i = 0, len = this.length; i < len; i++) {
this[i].checked = false;
}
break;
}
return this;
};
To toggle all, call with (for example):
document.getElementsByClassName('something').check('toggle');.
To check all, call with (for example):
document.getElementsByClassName('something').check('check');.
To uncheck all, call with (for example):
document.getElementsByClassName('something').check('uncheck');.

How to Disable whole Div Contents without using JQuery

As I have Basic knowledge of JavaScript I want to do operation like following :
By using Two radio button giving two option for Payment :
By Cash
By Check
If user select the radio button of Cash the Cheque Button should also disable and the Div of Cheque in which the details like cheque no and bank name is should also disable.
And visa Versa
Is there a way to do that without using JQuery? (disable a div and get all content disabled also)
Thanks in Advance For Help.
Try this:
document.getElementById("myDivId").disabled = true;
To disable all elements inside the div, try this:
var allChildNodes = document.getElementById("myDivId").getElementsByTagName('*');
for(var i = 0; i < allChildNodes.length; i++)
{
allChildNodes[i].disabled = true;
}
This code will disable all elements within the given container.
var container = document.getElementById("cashContainer");
var inputs = document.getElementsByTagName("input").concat(document.getElementsByTagName("select"));
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
Applying the same code you can re-enable the other container.
You may try this
HTML
<input type="radio" name="cashcheck" value="cash" checked />Cash<br />
<div id="cash">
<form method="post">
<input type="text" name="cashTxt1" />
<input type="text" name="cashTxt2" />
</form>
</div>
<input type="radio" name="cashcheck" value="check" />Check<br />
<div id="check">
<form method="post">
<input type="text" name="checkTxt1" disabled />
<input type="text" name="checkTxt2" disabled />
</form>
</div>
JS
window.onload=function(){
var radios = document.getElementsByName('cashcheck');
radios[0].onchange=toggle;
radios[1].onchange=toggle;
};
function toggle()
{
if(this.checked)
{
var div = document.getElementById(this.value),
inputs = div.getElementsByTagName('form')[0].getElementsByTagName('*');
for( var i=0; i<inputs.length; i++)
{
inputs[i].removeAttribute('disabled');
}
var op = this.value == 'cash' ? 'check' : 'cash',
divOp = document.getElementById(op),
divOpInputs = divOp.getElementsByTagName('form')[0].getElementsByTagName('*');
for( var i=0; i<divOpInputs.length; i++)
{
divOpInputs[i].setAttribute('disabled');
}
}
}
DEMO.
<fieldset disabled="true">
<div>
<input type="text" />
</div>
<br>
<div>
<input type="text" />
</div>
<br>
<div>
<input type="text" />
</div>
<br>
</fieldset>

Categories