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/>
Related
I have a page with characters, I want to display the characters with a black hair color when user clicks on the radiobutton
<div id="filters">Filters settings</br>
<p>Hair color</p>
<input type="radio" id="AllHair" name="HairColor" value="AllHair">
<label for="AllHair">Show all hair</label>
<input type="radio" id="BlondeHair" name="HairColor" value="BlondeHair">
<label for="BlondeHair">Show blonde hair</label>
<input type="radio" id="BlackHair" name="HairColor" value="BlackHair">
<label for="BlackHair">Show black hair</label>
</div>
This is my Javascript I have so far, idk how to finish it
function SortByHairColor(){
let retourString = `<tr class="row" style="background-color: ${colors[house]}">
<td id="column" class="column">${name}</td>
<td id="column" class="column">${actor}</td>
<td id="column" class="column"><img src="${image}"/></td>
</tr>`;
for (let i= 0; i < rdbHairColor.length; i++){
if (rdbHairColor[i].checked){
retourString += rdbHairColor[i];
break;
}
}
divToonGeslacht.innerHTML = retourString;
}
My init function
function Init()
{
debugger;
//start page
const text = potterCharacters.map(character => {
const { name, actor, image, house} = character
return `<tr class="row" style="background-color: ${colors[house]}">
<td id="column" class="column">${name}</td>
<td id="column" class="column">${actor}</td>
<td id="column" class="column"><img src="${image}"/></td>
</tr>`
})
document.getElementById("rows").innerHTML = text ;
filters = document.getElementById("filters");
rdbHairColor = document.querySelectorAll('input[name="HairColor"][type="radio"]');
rdbHairColor.addEventListener('change',SortByHairColor);
}
I updated my answer. Here you can see how I use array.filter() to find the characters with the selected haircolor.
HTML
<p>Please select haircolor</p>
<div>
<input type="radio" id="hair1" name="haircolor" value="black">
<label for="hair1">black</label>
<input type="radio" id="hair2" name="haircolor" value="red">
<label for="hair2">red</label>
<input type="radio" id="hair1" name="haircolor" value="brown">
<label for="hair3">brown</label>
</div>
<table id="result"></table>
JAVASCRIPT
const resultField = document.querySelector("#result")
const radioButtons = document.querySelectorAll('input[name="haircolor"][type="radio"]')
let potterCharacters = [{name:"ron", haircolor:"red"}, {name:"hermione", haircolor:"brown"}, {name:"harry", haircolor:"black"}, {name:"snape", haircolor:"black"}]
for(let btn of radioButtons) {
btn.addEventListener("change", (e) => updateSelection(e))
}
function updateSelection(e) {
resultField.innerHTML = `<tr><td>NAME</td><td>HAIRCOLOR</td></tr>`
let selection = potterCharacters.filter(char => char.haircolor == e.target.value)
for(let character of selection) {
let tr = document.createElement("tr")
tr.innerHTML = `<td>${character.name}</td><td>${character.haircolor}</td>`
resultField.appendChild(tr)
}
}
Check the JSFiddle here :)
In my page have a modal window, in the modal i have 2 checkboxes, i want if all checkboxes selected enabled send button and change background color (if disabled bgcolor is gray else bgcolor red). How i can it right way ?
HTML:
<form action="" method="POST" class="send-modal-data">
<input type="text" id="send_email" name="subscribe-email" class="modal-input" placeholder="Email *" required="required">
<div class="checkboks custom-sq vdc-cb-area">
<input type="checkbox" id="box4" name="vdc-modal-cb" class="checked-checkbox"/>
<label for="box4" class="checkboks-text d-flex align-center"><?php echo the_field('vdc_checkbox_txt', 'option'); ?></label>
</div>
<div class="checkboks custom-sq vdc-cb-area">
<input type="checkbox" id="box7" name="vdc-modal-cb" class="checked-checkbox" />
<label for="box7" class="checkboks-text d-flex align-center"><?php echo the_field('vdc_checkbox_text_2', 'option'); ?></label>
</div>
<div class="success-msg">
<div class="msg"></div>
</div>
<input type="submit" name="subscribe-form" id="vdc-send-modal" class="danger-btn send-subscribe" disabled="disabled" value="<?php echo the_field('lets_get_started', 'option'); ?>"></input>
</form>
JS:
var checks = document.getElementsByName('vdc-modal-cb');
var checkBoxList = document.getElementById('vdc-cb-area');
var sendbtn = document.getElementById('vdc-send-modal');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
checkBoxList.addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
console.log(123);
});
NOTE: I took this example from the stack overflow but it doesn't work for me
1.You should use getElementsByClassName to get elements with the same class.
2.To add eventListener to the class elements, you should iterate over the elements.
var checks = document.getElementsByName('vdc-modal-cb');
var checkBoxList = document.getElementsByClassName('vdc-cb-area');
var sendbtn = document.getElementById('vdc-send-modal');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
for (var i = 0; i < checkBoxList.length; i++) {
checkBoxList[i].addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
});
}
I need to validate radio buttons and I am struggling to find where the problem is coming from.
Basically put, what happens when I submit, it does not validate the form and all it's fields. I know it is this function that is causing the problem, because when it is taken out of the .js file the form validates properly.
Below is the part of my HTML file containing the radio buttons
<tr>
<th align="left">Driver Required: </th>
<td>
<input type="radio" name="Driver" value="Yes" id="radio_error"> Yes
</td>
</tr>
<tr>
<td><br></td>
<td>
<input type="radio" name="Driver" value="No" id="radio_error"> No
</td>
</tr>
<tr><th><br></th></tr>
<tr>
<th align="left">Insurance: </th>
<td>
<input type="radio" name="Insurance" value="None" id="radio_error"> None
</td>
</tr>
<tr>
<td><br></td>
<td>
<input type="radio" name="Insurance" value="CDW" id="radio_error"> Collision Damage Waiver
<br>
<input type="radio" name="Insurance" value="LI" id="radio_error"> Liability Insurance
<br>
<input type="radio" name="Insurance" value="PAI" id="radio_error"> Personal Accident Insurance
<br>
<input type="radio" name="Insurance" value="PEC" id="radio_error"> Personal Effects Coverage
</td>
</tr>
The following lines of code is from the .js file. I have a validate function, which I am sure isn't the problem.
function checkDriverRadio()
{
var yesOrNo = "";
var len = document.ClientForm.Drvier.length;
var i;
for (i = 0; i < len; i++)
{
if (document.ClientForm.Drvier[i].checked)
{
yesOrNo = document.ClientForm.Driver[i].value;
break;
}
}
if (!document.ClientForm.Driver.checked)
{
document.getElementById("radio_error").innerHTML = "No option selected";
return false;
}
else
{
document.getElementById("radio_error").innerHTML = "";
return true;
}
}
function checkInsuranceRadio()
{
var option = "";
var len = document.ClientForm.Insurance.length;
var i;
for (i = 0; i < len; i++)
{
if (document.ClientForm.Insurance[i].checked)
{
option = document.ClientForm.Insurance[i].value;
break;
}
}
if (!document.ClientForm.Insurance.checked)
{
document.getElementById("radio_error").innerHTML = "No option selected";
return false;
}
else
{
document.getElementById("radio_error").innerHTML = "";
return true;
}
}
I think there is a misspelling error...
if (document.ClientForm.Drvier[i].checked)
{
yesOrNo = document.ClientForm.Driver[i].value;
break;
....your file name is Driver not Drvier.
I hope this helps.
I realize all your radio buttons have the same Id's, Radio buttons are grouped by name="someName" which you have done and as mentioned by other answers you have some typographical errors you need to look at. I created a simple validation in this fiddle kindly check it out if it helps.
https://jsfiddle.net/mr_odoom/17xwdL79/
I have multiple checkboxes
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
</div>
How to find all checked checkboxes and create json or array with result of checking?
In case you just want to use pure/vanilla JS, here is an example:
HTML HEAD
<script type="text/javascript">
function getCheckedCheckboxesFor(checkboxName) {
var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
return values;
}
</script>
HTML BODY
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
<input type="button" onclick="alert(getCheckedCheckboxesFor('employee'));" value="Get Values" />
</div>
JS Fiddle link: http://jsfiddle.net/dY372/
Try this:
Fiddle
jQuery:
var selected = [];
$('.data input:checked').each(function() {
selected.push($(this).val());
});
Javascript:
var checkboxes = document.getElementsByName('employee');
var selected = [];
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
selected.push(checkboxes[i].value);
}
}
Using querySelectorAll:
var checked = document.querySelectorAll('[name="employee"]:checked');
Support: IE9+.
var elements=document.getElementsByName('employee');
should return you an array of the elements you require
DEMO
function checked(){
var items=getElementsByname('checkbox');
var selectedlist=[];
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedlist+=items[i].value+"\n";
}
alert(selectedlist);
}
<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+"&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>