(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/
Related
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>
I have a div as follows:
<div class="questionholder" id="question5" style="display:none">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
The user is expected to select all the checkboxes that apply to his situation. Let's assume he selects all 3.
When he clicks "Next", the function displayquestion(); will fire.
function displayquestion(a) {
var Elements = '';
var b = a - 1;
Elements = document.querySelector("#question" + b + " input[name=ID1element]").value;
}
Basically, the function is meant to store all the checked values into var Elements, which is meant to be an array.
However, I'm only getting the value of the first selected answer instead of an array of all selected answers.
How do I grab all the selected answers into an array?
No jQuery please.
Use querySelectorAll to get an array-like NodeList instead of querySelector, and then you can use Array.from to transform that NodeList into an array containing only the .value of the selected inputs:
function displayquestion(a) {
const b = a - 1;
const elements = Array.from(
document.querySelectorAll('#question' + b + ' input:checked'),
input => input.value
);
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
Here is the script that you can use for that:
I haven't changed anything in your HTML structure. Except I have removed the display: none; from the style attribute of the class questionholder.
<script>
function displayquestion(b) {
let checkboxList = document.querySelectorAll("#question" + b + " input:checked");
let obj = [];
if (checkboxList.length > 0) { //Code works only if some checbox is checked
checkboxList.forEach(function(item) {
obj.push(item.value); //Contains the value of all the selected checkboxes.
});
}
console.log(obj); //array list containing all the selected values
}
</script>
<div class="questionholder" id="question5" style="">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(5);">Next</a>
</div>
Here is a JSFiddle link for that.
I hope this is helpful.
So first of I would make a variable for your
<a class="text2button">Next</a>. And I have removed the
onclick="displayquestion(6)" from your html.
Here is the variable.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
Here we have the function, so what I've done is.
I have created a variable var elements = []; Which is a empty array.
Then I create this variable var inputs = document.getElementsByClassName("input5");
This variable gets all the inputs with class input5.
Next I would loop through each of the inputs from the var inputs. Like this.
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
So what I do here is loop through each input for (var i = 0; i < inputs.length; i++) and then I check if any of the inputs are checked if (inputs[i].checked), then I push them to the array var elements with elements.push(inputs[i].value);.
And then I use console.log(elements); so show it in the console.
Check out the snippet below to see it in effect.
Hope this helps.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
function displayquestion() {
var elements = [];
var inputs = document.getElementsByClassName("input5");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button">Next</a>
</div>
Trying to validate a multi-form data. If class "a" is checked it has to check whether class "b" is empty or not.
c = 1;
d = 1;
$('.a').each(function() {
if ($(this).is(':checked')) {
$('.b').each(function() {
if ($(this).val() == '') {
err += "<p>Value Empty at row +c+</p>";
return false;
}
d = d + 1;
});
}
c = c + 1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" class="a" name="a[]" value="Value" /> Value</label><br> <input type="text" class="b" name="b[]" />
The Issue is, it validates perfectly for the first form. when it comes to second form, it checks the first value of class 'b' instead of checking second value of class 'b'
You don't want the .b loop inside the .a loop. You want a single loop handling both:
var checkboxes = $(".a");
var textboxes = $(".b");
for (var n = 0; n < checkboxes.length; ++n) {
if (checkboxes[n].checked && !textboxes[n].value.trim()) {
err += "<p>Value Empty at row " + n + "</p>";
}
}
Live Example:
$("#btn").on("click", function() {
var err = "";
var checkboxes = $(".a");
var textboxes = $(".b");
for (var n = 0; n < checkboxes.length; ++n) {
if (checkboxes[n].checked && !textboxes[n].value.trim()) {
err += "<p>Value Empty at row " + n + "</p>";
}
}
$("#err").html(err);
});
<label><input type="checkbox" class="a" name="a[]" value="Value" /> Value</label><br> <input type="text" class="b" name="b[]" />
<br>
<label><input type="checkbox" class="a" name="a[]" value="Value" /> Value</label><br> <input type="text" class="b" name="b[]" />
<br>
<label><input type="checkbox" class="a" name="a[]" value="Value" /> Value</label><br> <input type="text" class="b" name="b[]" />
<br>
<input type="button" id="btn" value="Check">
<div id="err"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A couple of notes:
When you use [n] to index into a jQuery object, you get the raw DOM element at that position. When you have the raw element, there's no need for .is(":checked"), just use the checked property on the element itself. (So: checkboxes[n].checked instead of $(checkboxes[n]).is(":checked") or checkboxes.eq(n).is(":checked").)
Similarly, input elements have their own value property, no need to wrap them in an jQuery object just to call val().
My code above assumes that an input containing only whitespace should be considered empty. It does that with String#trim, which was introduced in ES5 (2009). If you need to support seriously obsolete browsers like IE8, you may need a polyfill for it.
When you use the code
$(".b")...
it checks all inputs with class b, but you only want the related one. The key is determining how they are related. It could be they are in a parent div or they could be matched using data- attributes, or could simply be the "next" input.
Your example HTML only shows one 'pair' of .a and .b, so if we expand that pair to multiple pairs, eg grouped in a 'group' div, you can then use .closest(".group") to find the containing div and then the related .b within that div:
$("#validate").click(function() {
var c = 1;
var d = 1;
var err = "";
$('.a').each(function() {
if ($(this).is(':checked')) {
// only find the related `.b`
//$('.b').each(function() {
$(this).closest(".group").find(".b").each(function() {
if ($(this).val() == '') {
err += "<p>Value Empty at row " + c + "</p>";
return false;
}
d = d + 1;
});
}
c = c + 1;
});
console.log("c:", c, "d:", d, err);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='group'>
<label>
<input type="checkbox" class="a" name="a[]" value="Value" />
Value
</label>
<br>
<input type="text" class="b" name="b[]" />
</div>
<div class='group'>
<label>
<input type="checkbox" class="a" name="a[]" value="Value" />
Value
</label>
<br>
<input type="text" class="b" name="b[]" />
</div>
<button id='validate' type='button'>validate</button>
When you're doing $('.b').each(function(){}) it's finding all the elements with class .b again/each time. Hence checking for first element again.
One solution would be to first find all the elements and then run the loop and use index to find the elements
as = $(".a");
bs = $(".b");
for(var i = 0; i < as.length; i++){
a = as[i];
b = bs[i];
if($(a).is(':checked')){
if($(b).val() === ''){
err += "<p>Value Empty at row +c+</p>";
return false;
}
}
}
Or structure your markup a in such a way where all the related elements with class a & b are put inside a div.
You can find all the .a and while looping you'll find all the .b inside the parent div
<div class='wrapper-related-fields'>
<label><input type="checkbox" class="a" name="a[]" value="Value" /> Value</label>
<br>
<input type="text" class="b" name="b[]" />
</div>
$('.a').each(function(){
if($(this).is(':checked')){
// Find the parent wrapper
wrapper = $(this).closest(".wrapper-related-fields");
// find all the .b elements inside wrapper
$(warpper).find('.b').each(function(){
if($(this).val() == '')
{
err += "<p>Value Empty at row +c+</p>";
return false;
}
d = d + 1;
});
}
c = c + 1;
});
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');.
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
I need a javascript validation to check whether any checkbox is selected or not?
Thanks and Regards
NOTE: I need javascript validation
You can access the DOM elements and check their checked property. For instance:
var list, index, item, checkedCount;
checkedCount = 0;
list = document.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
item = list[index];
if (item.getAttribute('type') === "checkbox"
&& item.checked
&& item.name === "midlevelusers[]") {
++checkedCount;
}
}
Live example
There we're looking through the whole document, which may not be efficient. If you have a container around these (and presumably you do, a form element), then you can give that element an ID and then look only within it (only the var, form =, and list = lines are new/different):
var form, list, index, item, checkedCount;
checkedCount = 0;
form = document.getElementById('theForm');
list = form.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
item = list[index];
if (item.getAttribute('type') === "checkbox"
&& item.checked
&& item.name === "midlevelusers[]") {
++checkedCount;
}
}
Live example
Off-topic: You haven't mentioned using a library, so I haven't used one above, but FWIW this stuff is much easier if you use one like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:
var checkedCount = $("input[type=checkbox][name^=midlevelusers]:checked").length;
Live example Other libraries will be similar, though the details will vary.
<form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
<input type="checkbox" name="midlevelusers[]" value="1" /> 1
<input type="checkbox" name="midlevelusers[]" value="2" /> 2
<input type="checkbox" name="midlevelusers[]" value="3" /> 3
<input type="checkbox" name="midlevelusers[]" value="4" /> 4
<input type="checkbox" name="midlevelusers[]" value="5" /> 5
<input type="submit" value="Submit Form" />
</form>
<script type="text/javascript">
function checkTheBox() {
var flag = 0;
for (var i = 0; i< 5; i++) {
if(document.myform["midlevelusers[]"][i].checked){
flag ++;
}
}
if (flag != 1) {
alert ("You must check one and only one checkbox!");
return false;
}
return true;
}
</script>
try,
function validate() {
var chk = document.getElementsByName('midlevelusers[]')
var len = chk.length
for(i=0;i<len;i++)
{
if(chk[i].checked){
return true;
}
}
return false;
}
use id's
<input type="checkbox" name="midlevelusers[]" id="mlu1" value="1">
<input type="checkbox" name="midlevelusers[]" id="mlu2" value="2">
<input type="checkbox" name="midlevelusers[]" id="mlu3" value="3">
<input type="checkbox" name="midlevelusers[]" id="mlu4" value="4">
now you can do
for (var i=1;i<5;i++){
var el = document.getElementById('mlu'+i);
if (el.checked) { /* do something */}
}
This function would alert whether or not a checkbox has any values checked.
function isChecked(checkboxarray){
for (counter = 0; counter < checkboxarray.length; counter++){
if (checkboxarray[counter].checked){
alert("Checkbox has at least one checked");
else{
alert("None checked");
}
You would need to add a bit more to do what you actually want to do with it but that will get you on the right track I think!
You could use jQuery and do it this way:
if($('input[name="light[]"]:checked').length < 1){
alert("Please enter the light conditions");
}