How to count checked checkboxes in different divs - javascript

<head><title>STUDENT WISE EXAM BACKLOGS DISPLAY FOR EXAM REGISTRATION</title>
<style type="text/css">
th {
font-family:Arial;
color:black;
border:1px solid #000;
}
thead {
display:table-header-group;
}
tbody {
display:table-row-group;
}
td {
border:1px solid #000;
}
</style>
<script type="text/javascript" >
function check_value(year,sem){
ysem="ys"+year+sem;
var reg=document.registration.regulation.value;
subjectsys="subjects"+year+sem;
amountsys="amount"+year+sem;
if(year==1){
if(sem==1){
var value_list = document.getElementById("ys11").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys12").getElementsByTagName('input');
}
}elseif(year==2){
if(sem==1){
var value_list = document.getElementById("ys21").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys22").getElementsByTagName('input');
}
}elseif(year==3){
if(sem==1){
var value_list = document.getElementById("ys31").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys32").getElementsByTagName('input');
}
}elseif(year==4){
if(sem==1){
var value_list = document.getElementById("ys41").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys42").getElementsByTagName('input');
}
}
values = 0;
for (var i=0; i<value_list.length; i++){
if (value_list[i].checked) {
values=values+1;
}
}
document.getElementById(subjectsys).value=values;
if (values=="0")
{
document.getElementById(amountsys).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(amountsys).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","fee.php?year="+year+"&reg="+reg+"&sem="+sem+"&sub="+values,true);
xmlhttp.send();
}
</script>
</head>
<form id="registration" name="registration" action=subverify.php method=POST></br></br> <center> Backlog Subjects for <b>My HtNo</b>
</br></br>
<table border='1'><tr>
<th width='40'> </th><th width='90'>Regulation</th><th width='40'>Year</th>
<th width='40'>Sem</th><th width='350'>Subname</th>
<th width='70'>Internals</th><th width='70'>Externals</th>
</tr><div id="ys41"><tr>
<td width='40'><center><input type="checkbox" name="sub[]" value="344"
onclick="check_value(4,1)"></center></td>
<td width='90'><center>R07</center></td><td width='40'><center>4</center></td><td width='40'><center>1</center></td>
<td width='350'>EMBEDDED SYSTEMS</td><td width='70'><center>18</center></td>
<td width='70'><center>17</center></td></tr><tr><td colspan=5 align=right><b>Subjects: </b><input size=2 type=textbox id=subjects41 name=subjects41 value=0 maxlength=2 readonly=readonly></td>
<td align=right><b>Amount :</b></td>
<input type='hidden' name='regulation' id=regulationsubjects41 value='R07'>
<td><div id="amount41"><input type="textbox" name="amountval41" value="0" size="5" maxlength="5" readonly="readonly"></div></td></tr></div><div id="ys42"><tr>
<td width='40'><center><input type="checkbox" name="sub[]" value="527"
onclick="check_value(4,2)"></center></td>
<td width='90'><center>R07</center></td><td width='40'><center>4</center></td><td width='40'><center>2</center></td>
<td width='350'>DESIGN PATTERNS</td><td width='70'><center>12</center></td>
<td width='70'><center>14</center></td></tr><tr><td colspan=5 align=right><b>Subjects: </b><input size=2 type=textbox id=subjects42 name=subjects42 value=0 maxlength=2 readonly=readonly></td>
<td align=right><b>Amount :</b></td>
<input type='hidden' name='regulation' id=regulationsubjects42 value='R07'>
<td><div id="amount42"><input type="textbox" name="amountval42" value="0" size="5" maxlength="5" readonly="readonly"></div></td></tr></div><tr><td colspan=7><center><b><div id="maintotal"><input type="textbox" name="maintotal" value="0" size="5" maxlength="5" readonly="readonly"></div></center></b></td></tr><tr></tr></table></br></br> <center><input type='hidden' name='htno' value='08KN1A1219'>
<input type='submit' value='Register'></center></form></br>
This is a output of a PHP file with using dynamic data in the form.
I want to count only the checkboxes in the <div> tag and it has to display in that subjects <div> tag like subjects41 and subjects42. Can anyone please help me to update this JavaScript? It passes some ajax request for displaying the fee.

$("input[type=checkbox]:checked").length

You can use simple jquery something like this
var count=0;
$("input[type=checkbox]").each(function(){
if(this.is(":checked")){
count+=1;
}
})
alert(count);

Using jQuery ,
var ids = $('input[name="nameofcheckbox[]"]:checked')
.map(function(){
return this.value;
}).get();

Without Jquery:
var div = document.getElementById("ys41");
var checkboxes = [];
function getCheckBoxes(el) {
//check this is an element
if (el.nodeType == 1) {
var i = 0;
//get the children
var elements = el.childNodes;
// Loop through children
while (typeof elements[i] !== 'undefined') {
//check this is an element
if (elements[i].nodeType == 1) {
// If the type is checkbox add it to the array
if (elements[i].getAttribute('type') == 'checkbox') {
checkboxes[checkboxes.length] = elements[i];
}
// Otherwise recurse
else {
if (elements[i].childNodes.length > 0) {
getCheckBoxes(elements[i]);
}
}
}
i++;
}
}
}
getCheckBoxes(div);
Caveat: I don't have time right now to check that this works ;). If it doesn't comment and I'll correct this evening.

Since you wanted to do this using javascript,
<FORM>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="1"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="2"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="3"><br>
<INPUT TYPE=button NAME="CheckAll" VALUE="checkbox count" onClick="modify_boxes()">
</FORM>​
function modify_boxes(){
var total_boxes = document.forms[0].chkboxarray.length;
var count =0;
for ( i=0 ; i < total_boxes ; i++ ){
if (document.forms[0].chkboxarray[i].checked ==true)
count++;
}
alert(count);
}​​​​
Working Demo

here you go, this's what you asked :)
var i=0;
var checks= 0;
divelem = document.getElementById("divelem");
while(i < divelem.childNodes.length){
if( divelem.childNodes[i].nodeType != 3 //not empty space
&& divelem.childNodes[i].getAttribute('type') == 'checkbox' //is checkbox?
&& divelem.childNodes[i].checked ){ // is checked?
checks++;
}
i++;
}
alert("no of checkboxes checked in div are: "+checks);
I prefer you count in the php itself.
UPDATE:
here's the complete code, I am damn sure it's working. It gives all checkboxes that are checked in all div elements. Pls check.
<html>
<div >
1.<input type="checkbox" value="check1" / ></br>
2.<input type="checkbox" value="check2" / ></br>
3.<input type="checkbox" value="check3" / ></br>
</div>
<div >
4.<input type="checkbox" value="check4" / ></br>
5.<input type="checkbox" value="check5" / ></br>
</div>
<input type="button" value="count check" onclick="check()">
<script>
function check(){ //function can count checkboxes for all div elements in document
var checks= 0;
var divelems = document.getElementsByTagName('div');
for(no=0;no<divelems.length;no++){
var i=0;
while(i < divelems[no].childNodes.length){
if( divelems[no].childNodes[i].nodeType != 3 //not empty space
&& divelems[no].childNodes[i].getAttribute('type') == 'checkbox' //is checkbox?
&& divelems[no].childNodes[i].checked ){ // is checked?
checks++;
}
i++;
}
}
alert("no of checkboxes checked inside div are: "+checks);
}
</script>
</html>
UPDATE2:
pls check now
<html>
<script>
function check(div){ //function can count checkboxes for divs elements that is passed in as argument
var checks= 0;
var divelem = document.getElementById(div);
var i=0;
while(i < divelem.childNodes.length){
if( divelem.childNodes[i].nodeType != 3 //not empty space
&& divelem.childNodes[i].getAttribute('type') == 'checkbox' //is checkbox?
&& divelem.childNodes[i].checked ){ // is checked?
checks++;
}
i++;
}
alert("no of checkboxes checked inside "+div+" are: "+checks);
}
</script>
<div id="div1" >
1.<input type="checkbox" value="check1" / ></br>
2.<input type="checkbox" value="check2" / ></br>
3.<input type="checkbox" value="check3" / ></br>
<input type="button" value="count check div1" onclick="check('div1')">
</div>
<div id="div2" >
4.<input type="checkbox" value="check4" / ></br>
5.<input type="checkbox" value="check5" / ></br>
</div>
<input type="button" value="count check div2 " onclick="check('div2')">
</html>

Related

javascript disable checkbox when another checkbox is checked with same name [duplicate]

I have a group of check boxes with same name, what I need is when I click any one of them, other checkboxes must get disabled. how should I apply Javascript over it?
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
Please help...
You could do
$('input').attr('disabled',true);
...if you really need it. But you might be better off using radio buttons.
Try the demo
<script type="text/javascript">
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].checked !=true)
document.test.finallevelusers[i].disabled='true';
}
</script>
probably you want them enabled again when user uncheck the checkbox
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].disabled ==true)
document.test.finallevelusers[i].disabled='false';
}
<script type="text/javascript">
function disableHandler (form, inputName) {
var inputs = form.elements[inputName];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.onclick = function (evt) {
if (this.checked) {
disableInputs(this, inputs);
}
else {
enableInputs(this, inputs);
}
return true;
};
}
}
function disableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = true;
}
}
}
function enableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = false;
}
}
}
</script>
</head>
<body>
<form name="aForm" action="">
<p>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
</p>
</form>
<script type="text/javascript">
disableHandler(document.forms.aForm, 'finallevelusers[]');
</script>
Hope This solution helps you-
your DOM could be something like this :
<div class="checkboxes">
<input type="checkbox" name="sameCheck" class="checkbox" id="1" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="2" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="3" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="4" onchange="checkChange()">
</div>
And your logic is this :
let checkbox = document.querySelectorAll('.checkbox')
let b = false;
function checkChange(){
b = !b
if(b){
for(let i = 0 ; i< checkbox.length; i++){
if(checkbox[i].checked === false){
checkbox[i].disabled = 'true';
}
}
}else{
for(let i = 0 ; i< checkbox.length; i++){
checkbox[i].removeAttribute('disabled');
}
}
}
Try code like this
<script>
function uncheck(){
for(var ii=1; ii<=4; ii++){
if(document.getElementById("q6_"+ii).checked==true){
document.getElementById("q6_"+ii).checked=false;
}
}
}
</script>

Set a condition for elements with the same class in javascript

I have a couple of checkboxes that I want to check if the user selected them,
If he selected 2, then he can't select more.
The problem is that I use the them several times in diffrent rows and they have the same class.
How can I check in javascript if only 2 checkboxes are selected in each group of buttons?
HTML:
<td>
<!-- First Group of Buttons -->
<p>Barcelona</p>
<label class="dir-bet" type="checkbox">Barcelona Win</label>
</td>
<td class="middle-table">
<p>VS</p>
<label class="dir-bet" type="checkbox">Draw</label>
</td>
<td class="team-header">
<p>R.Madrid</p>
<label class="dir-bet" type="checkbox">R.MadridWin</label>
</td>
</tr>
<tr>
<td>
<!-- Second Group of Buttons -->
<p>Barcelona</p>
<label class="dir-bet" type="checkbox">Barcelona Win</label>
</td>
<td class="middle-table">
<p>VS</p>
<label class="dir-bet" type="checkbox">Draw</label>
</td>
<td class="team-header">
<p>R.Madrid</p>
<label class="dir-bet" type="checkbox">R.Madrid Win</label>
</td>
Java-Script:
var list = document.getElementsByClassName("dir-bet");
var checkBet = function(){
var checkNum = 0;
for (i = 0; i < list.length; i++){
if(list[i].getAttribute("checked")){
checkNum++;
}
}
if (checkNum<2 ) {
if(this.getAttribute("checked")){
this.setAttribute("checked","");
this.classList.remove ("prime-bg", "prime-clr");
}else{
this.setAttribute("checked","true");
this.classList.add ("prime-bg", "prime-clr");
}
}else{
if(this.getAttribute("checked")){
this.setAttribute("checked","");
this.classList.remove ("prime-bg", "prime-clr");
}
}
};
for (i = 0; i < list.length; i++){
list[i].addEventListener("click", checkBet);
}
You could check in which table row your click happens, and then get only the list of dir-bet class elements that are within that row. Then apply your counting logic on that smaller list of elements.
With some other improvements, your checkBet function could look like this:
var checkBet = function () {
var checked = this.getAttribute("checked");
if (!checked) { // a count is only needed when adding a check mark:
var list = this.parentElement.parentElement.getElementsByClassName("dir-bet");
var checkNum = 0;
for (var i = 0; i < list.length; i++) {
if (list[i].getAttribute("checked")) {
checkNum++;
}
}
if (checkNum >= 2) return; // reject
}
// toggle the check status
checked = !checked;
this.setAttribute("checked", checked ? "true" : "");
this.classList.toggle("prime-bg", checked);
this.classList.toggle("prime-clr", checked);
};
If jQuery is an option, here's a solution :
let $checkboxes = $("input[type=checkbox]")
$checkboxes.click(() => {
$checkboxes.attr("disabled", false)
if ($("input[type=checkbox]:checked").length == 2) {
$("input[type=checkbox]:not(:checked)").attr("disabled", true)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Can check only 2 checkboxes</h2>
<br/>
<input type="checkbox"/><span>Checkbox 1</span><br/>
<input type="checkbox"/><span>Checkbox 2</span><br/>
<input type="checkbox"/><span>Checkbox 3</span><br/>
<input type="checkbox"/><span>Checkbox 4</span><br/>
<input type="checkbox"/><span>Checkbox 5</span><br/>
<input type="checkbox"/><span>Checkbox 6</span><br/>
<input type="checkbox"/><span>Checkbox 7</span><br/>
<input type="checkbox"/><span>Checkbox 8</span><br/>
<input type="checkbox"/><span>Checkbox 9</span><br/>
<input type="checkbox"/><span>Checkbox 10</span><br/>

change redirect location onClick.

I'm trying to change a redirect link using check boxes that append to the URL and a button that uses the changed URL. Im still a beginner to JavaScript and am a little lost as to where i'm going wrong.
My code:
<html>
<form>
<div class="element1">"
<input type="checkbox" name="name1" id="id1" value="val1" class="hidden" ></label></div>
<div class="element2">"
<input type="checkbox" name="name2" id="id2" value="val2" class="hidden" ></label></div>
<div class="element3">"
<input type="checkbox" name="name3" id="id3" value="val3" class="hidden" ></div>
<div class="element00">
<input type="button"onclick="myFunction(calculatedUrl());" name="button1" id="itemA" value="valA" ></label></div>
</form>
<script>
function calculatedUrl(){
var totalString=""
var link1="some text"
var link2="more text"
var link3="something else"
if(document.getElementById("id1").checked == true){
var totalString = totalString.concat(link1);
}
if(document.getElementById("id2").checked == true){
var totalString = totalString.concat(link2);
}
if(document.getElementById("id3").checked == true){
var totalString = totalString.concat(link3);
}
return totalString
}
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
var new=original.concat(addition)
//for testing
window.alert(new)
document.getElementById("test1").innerHTML= new;
//for the real redirecting not active for now
//window.location=new
}
</script>
</html>
<html>
<form>
<div class="element1">"
<input type="checkbox" name="name1" id="id1" value="val1" class="hidden" ></label></div>
<div class="element2">"
<input type="checkbox" name="name2" id="id2" value="val2" class="hidden" ></label></div>
<div class="element3">"
<input type="checkbox" name="name3" id="id3" value="val3" class="hidden" ></div>
<div class="element00">
<input type="button"onclick="myFunction(calculatedUrl());" name="button1" id="itemA" value="valA" ></label></div>
</form>
<script>
function calculatedUrl(){
var totalString=""
var link1="some text"
var link2="more text"
var link3="something else"
if(document.getElementById("id1").checked == true){
var totalString = totalString.concat(link1);
}
if(document.getElementById("id2").checked == true){
var totalString = totalString.concat(link2);
}
if(document.getElementById("id3").checked == true){
var totalString = totalString.concat(link3);
}
return totalString
}
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
console.log(id);
var n =original.concat(addition)
//for testing
window.alert(n)
document.getElementById("test1").innerHTML= n;
//for the real redirecting not active for now
//window.location=new
}
</script>
</html>
Currently in your code change the below, new to newurl - new is a reserved word.
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
var newurl =original.concat(addition)
//for testing
window.alert(newurl)
document.getElementById("test1").innerHTML= newurl;
//for the real redirecting not active for now
//window.location=new
}
I dont see a tag with id=test1, so you will get null exception in the console browser. Add a tag based on that and test.
I have added a snippet, please check.
<html>
<form>
<div class="element1">"
<input type="checkbox" name="name1" id="id1" value="val1" class="hidden" ></label></div>
<div class="element2">"
<input type="checkbox" name="name2" id="id2" value="val2" class="hidden" ></label></div>
<div class="element3">"
<input type="checkbox" name="name3" id="id3" value="val3" class="hidden" ></div>
<div class="element00">
<input type="button"onclick="myFunction(calculatedUrl());" name="button1" id="itemA" value="valA" ></label></div>
</form>
<script>
function calculatedUrl(){
var totalString=""
var link1="some text"
var link2="more text"
var link3="something else"
if(document.getElementById("id1").checked == true){
var totalString = totalString.concat(link1);
}
if(document.getElementById("id2").checked == true){
var totalString = totalString.concat(link2);
}
if(document.getElementById("id3").checked == true){
var totalString = totalString.concat(link3);
}
return totalString
}
function myFunction(id){
var original="http://myoriginalurl"
var addition=id
console.log(id);
var n =original.concat(addition)
//for testing
window.alert(n)
document.getElementById("test1").innerHTML= n;
//for the real redirecting not active for now
//window.location=new
}
</script>
</html>

I don't know how to write dom document just once

I would like rewrite a dom document just once.
Html:
<body>
<form id="test">
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<td width="30%">?</td>
<td>
<input name="q1" type="checkbox" id="q1" value="R"/>
R
<input name="q1" type="checkbox" id="q1" value="T"/>
T
<input name="q1" type="checkbox" id="q1" value="Ra"/>
Ra
<input name="q1" type="checkbox" id="q1" value="Ho"/>
Ho
<input name="q1" type="checkbox" id="q1" value="F"/>
F
<input name="q1" type="checkbox" id="q1" value="Fr"/>
Fr
<input name="q1" type="checkbox" id="q1" value="Fo"/>
Fo
</td>
</tr>
</table>
<br/>
<input name="submit" type="button" onClick="gradeTest()" value="Com"/>
</form>
</body>
I tried with this:
function gradeTest() {
var a1 = document.getElementsByName('q1');
var a1answers = new Array();
var a1right = new Array('R','T','Ra');
var a1bool = true;
for(i = 0; i < a1.length; i++) {
if(a1[i].checked) {
a1answers.push(a1[i].value);
}
}
a1answers.sort();
a1right.sort();
if(a1answers.length == a1right.length) {
for(i = 0; i < a1answers.length; i++) {
if(a1answers[i] != a1right[i]) {
a1bool = false;
break;
}
}
}
else {
a1bool = false;
}
if(a1bool == true) {
var moveable = document.getElementById('test');
var s = '<p align="center"> <img border=0 src="arbol.png" width="250" /></p>';
var div = document.createElement('div');
div.innerHTML = s;
var elements = div.firstChild;
document.body.appendChild(elements);
var newParent = document.body.appendChild(document.createElement('test'));
newParent.removeChild(newParent.firstChild);
newParent.insertBefore(moveable, newParent.firstChild);
correctAnswers++;
}
}
When I execute this code, print a lot of images, but i want one.
In the line 6, i put test whiout test didn't work
Thank you
Check whether you've already appended the new element, and don't add it again.
if(a1bool == true) {
if (!document.getElementById("arbol")) {
var s = '<p align="center" id="arbol"> <img border=0 src="arbol.png" width="250" /></p>';
var div = document.createElement('div');
div.innerHTML = s;
var elements = div.firstChild;
document.body.appendChild(elements);
}
correctAnswers++;
}

show and hide div based on checkbox selection using javascript

Hi I have a requirement for hiding and displaying the division based on checkbox selection. Currently I have to show and hide 10 division and 10 checkbox is provided for that. Also there should be on checkbox selet all which will check all the checkbox and all 10 div should be displayed. Once user will click select all it should now change to deselect all to deselect all.Once de select all is clicked it will deselect all checkbox and no division should be displayed. Kindly provide me javascript solution not jquery.
Here is the code
<html>
<head>
<script type="text/javascript">
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;
}
checkflag = "true";
return "Uncheck All";
} else {
for (i = 0; i < field.length; i++) {
field[i].checked = false;
}
checkflag = "false";
return "Check All";
}
}
function ShowHideDiv(chkPassport) {
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = chkPassport.checked ? "block" : "none";
}
</script>
</head>
<body>
<form name=myform action="" method=post>
<table>
<tr>
<td><strong>Make a selection</strong><br> <input
type=checkbox name=list id="chkPassport"
onclick="ShowHideDiv(this)" value="1">Java<br> <input
type=checkbox name=list value="2">JavaScript<br> <input
type=checkbox name=list value="3">ASP<br> <input
type=checkbox name=list value="4">HTML<br> <input
type=checkbox name=list value="5">SQL<br> <br> <input
type=button value="Check All"
onClick="this.value=check(this.form.list)"></td>
</tr>
</table>
<div id="dvPassport" style="display: none">
Passport Number: <input type="text" id="txtPassportNumber" />
</div>
</form>
</body>
</html>
You can do so by the following jQuery code:
$('.checkbox').click(function() {
if( $(this).is(':checked')) {
$("#yourdiv").show();
} else {
$("#yourdiv").hide();
}
});
Change the #yourdiv - and .checkbox to your CSS identifiers.

Categories

Resources