Getting All HTML Checkboxes (Array) Checked with Javascript (and PHP) - javascript

I've been searching for this for a couple hours with no luck. This seems like it should be fairly easy but I am obviously overlooking something.
I have a table, with each row displaying information in each cell. At the end of each of the rows, there is an additional cell with a checkbox in it. The checkbox is an array, and each checkbox value is an imploded array via PHP. See below:
HTML/PHP
--------
(...some html code...)
<form method="post" action="the-next-page.php">
<table>
<tr>
<?php
(...some php SQL query code...)
while ($row = oci_fetch_array($result)) {
?>
<td><input type="text">Name</td>
<td><input type="text">City</td>
<td><input type="checkbox" name="checkGroup[]" value="<?php implode(":",$someArrayvariable) ?>"></td>
<?php
}
?>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
....
</html>
Passing the imploded values to the next page works fine. No problem there.
I have been trying to create a javascript function to check all of the boxes that are in this form, or under the checkbox group's name, or whatever I can do to check them all with the click of a button. I've tried variations of the following with no success:
HTML (On the top of the same script as above)
----
<button name="checkAll" onclick="checkAll()">Check All</button>
Javascript (On the bottom of the same script as above)
----
<script type="text/javascript">
function checkAll() {
var checks = document.getElementByName("checkGroup");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
</script>
I can't figure out what I'm doing wrong. I know that a variation of this question has been asked before many times, but I don't seem to be getting any results. I'm guessing because my checkboxes name is an array (checkGroup[] ???).
When I click the button to check all of the checkboxes in the form, nothing happens.
Any ideas? Thanks in advance.
-Anthony

You can use JQuery to make this easier on yourself.
I would also assign a general class name to each checkbox input, so then in Javascript (using JQuery):
$(".classname").each(function() {
$(this).prop("checked",true);
});
I would also give the Check All button a unique class/id so you can do this
$(document).ready(function() {
$("#allcheckboxid").on("click",function() {
$(".classname").each(function() {
$(this).prop("checked",true);
});
});
})

Two minor things:
function checkAll() {
var checks = document.getElementsByName("checkGroup[]");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
getElementByName should be getElementsByName, and checkGroup should be checkGroup[]. Other than that your code should be good to go!

Try this way to get all checked check box elements
<button name="checkAll" onclick="checkAll()">Check All</button>
<script type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('checkGroup[]');
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
</script>

Related

enable a disabled form

I have a form which is disabled using <fieldset disabled="disabled">. Now I want to enable the same form. I've used javascript but it isn't enabling my form. Here is my form and javascript code:
<?php echo "<input type='button' id='disable_enable_button' onclick='enableForm()' value='Enable/Disable'>"; ?>
<form id="form1>
<fieldset disabled="disabled">
<table>
<thead>
<tr>Sr no</tr>
<tr>Application</tr>
<tr>Comments</tr>
</thead>
<tbody>
<tr>1</tr>
<tr>ABC</tr>
<tr><textarea></textarea></tr>
</tbody>
</table>
</fieldset>
</form>
function enableForm() {
var form = document.getElementById("form1");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].readOnly = "";
}
}
I see a few potential issues here. I don't know how different your code here is than your actual file, but make sure that your JavaScript code is wrapped with <script></script> tags. In addition to this, I never see a call to the function enableForm(), (again, could be different in your actual code), although I see the function showForm() call a few times. Make sure this function is called, probably upon some user action (ie button click).
Feel free to comment on this with any issues/corrections, and I will help resolve them!

Toggle checkboxes on PHP table

I have a table with a checkbox in the table header, which will be used to toggle all the checkboxes below it. I've add a JavaScript function to the checkbox in the header, but so far it only selects the top checkbox (one checkbox) instead of all of them. Any suggestions or advice on what I've done wrong or what to research?
HTML table header code:
<thead>
<tr>
<th><center><input type="checkbox" value="" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"></center></th>
<th>Sender</th>
<th>Receiver</th>
<th>Subject</th>
<th>Date</th>
</tr>
</thead>
PHP table code:
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_1" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Javascript code:
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = document.getElementById(cbarray[i].id);
cb.checked = master.checked;
}
}
The problem is you setting the same ID (cb1_1) to all the checkboxes (which is invalid in HTML) Id should be unique in the page. Thus, it only select the first found checkbox and discard the rest. To resolve this give unique ids to checkboxes.
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_'.$pmid.'" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Note: I just use the $pmid just as an example you should use appropriate value as per your scenario
I see 2 issues with you code.
(Probably) using the same id for multiple DOM elements
Your PHP code suggests that you are probably using a loop to create the checkboxes but you are using the same id for all of them "cb1_1".
Same as #atul here.
Improperly selecting your checkbox elements
Since you are using the same id for all inputs,
var cb = document.getElementById(cbarray[i].id);always returns the same element. A way to solve it is to use the solution provided by #atul
Another way is to rewrite your javascript as follows :
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = cbarray[i];
cb.checked = master.checked;
}
}
Your cbarray is already your checkboxes array, so it is redundant (aka useless) to call document.getElementById(cbarray[i].id) to get the element when you already have it with cbarray[i].

quick html and JavaScript

<form action="#" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td><p> 1. </p></td>
<td><label> I am cool </label></td>
<div class="allQuestion">
<?php for($i=1; $i<=10; $i++){?><td><input type="radio" name="Dquestion[1]" value="<?=$i?>"> <?=$i?> </td> <?php } ?>
</div>
</tr>
</table><!-- strength_table end -->
<input type="submit" value="Submit"><br/>
</form>
js
function validateForm(){
var questions = document.getElementsByClassName("allQuestion");
for( var j=0; j<questions.length; j++){
if( !isOneInputChecked(questions[j], "radio")){
formValid = false;
}
}
alert(formValid ? "Submisson succesful!" : "Submisson Failed");
return formValid;
}
function isOneInputChecked(sel){
var inputs = sel.getElementsByTagName('input');
for(var k = 0; k < inputs.length; k++){
if(inputs[k].checked)
return true;
};
return false;
};
i am using this to validate my radio question , it work perfectly but once i put the <td> before <input> , it work weird , i know it target the all input warp by allQuestion and td is blocking it.
any idea how i keep the td in place and make the script works ?
i tryed this code but didt work
var questions = document.getElementsByClassName("allQuestion").getElementsByTag("Td");
Avoid using table elements as a layout. I know it seems convenient when you first start off, but save yourself the trouble and just go straight into learning to style with css
function validateForm(){
var checked = document.querySelector('form').elements.some(function(el){
return el.checked;
});
if(checked){
//at least one is checked
} else {
//none are checked
}
}
I didn't exactly test this, but just try to give an id to the td that u are targeted.
var questions = document.getElementsByTag("id_name"); //id_name is the id of the td
*just extra notes, using table is not a good practice, use other simple HTML and CSS for more flexibilty and readble code.

Loop through form input fields with Javascript

Please help me out on this. I have Javascript like the following:
function calc() {
var table = document.getElementById(tableNum);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum[i] = document.formNum.txt1[i].value * document.formNum.txt2[i].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}
And HTML like this:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[]" onkeyup="calc()"/></td>
<td><span id="totalCalc[]"></span></td>
</tr>
</form>
</table>
The number of input fields is unknown. No error, but totalCalc field is empty. Please tell me what I have done wrong. Thanks.
EDIT: I'm sorry, I forgot to mention both the input fields are in a table. Please check the edited code. Thanks.
EDIT: I'm actually working on a demo which the number of table row is defined by user, by clicking insert row button.
EDIT: Thanks Travis for the code. After a few changes, the code is working now. But only the first row is working. I'm thinking to get the length of the row and to use for loop for the text fields. <input type="text" name="txt1[<?php echo $rowLength;?>]" onkeyup="calc()"/> Does anyone have other ideas? Thanks.
The first thing seems wrong is
document.getElementById(tableNum);
should be
document.getElementById("tableNum");
Secondly,
var totalNum[i] =
should be
var totalNum =
Also, its not working, you can find it out quickly by debugging through firebug or chrome's integrated developer tool. Which will help you for syntax verification as well.
Here is what is going on.
HTML first
If you are going to reference these by indices, then use proper indices, like this
name="txt1[0]"
name="txt2[0]"
<span id="totalCalc[0]">
Javascript
document.getElementById(tableNum);
getElementsById expects a string, so this should be
document.getElementById("tableNum");
Since you are iterating, you only need one of these variables since it is immediately used (not a whole array):
var totalNum = instead of var totalNum[i]
When you access the form using dot notation, the brackets in the name messes that up, you need to do it like this:
document.formNum["txt1["+i+"]"].value instead of document.formNum.txt1[i].value
Vuala
When you make these minor changes, the code you used will actually produce proper results :) See this working demo: http://jsfiddle.net/69Kj7/ , also, here is a demo with 2 rows: http://jsfiddle.net/69Kj7/1/
For reference, this is the code in the demo:
html:
<table id="tableNum">
<form name="formNum" action="" id="formNum">
<tr>
<td><input type="text" name="txt1[0]" onkeyup="calc()"/></td>
<td><input type="text" name="txt2[0]" onkeyup="calc()"/></td>
<td><span id="totalCalc[0]"></span></td>
</tr>
</form>
</table>​
js:
function calc() {
var table = document.getElementById("tableNum");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var totalNum = document.formNum["txt1["+i+"]"].value * document.formNum["txt2["+i+"]"].value;
document.getElementById('totalCalc[' + i + ']').innerHTML = totalNum;
}
}​
if you wants to work with pure java script and here is the logical code
html
<form name="formNum" id="formNum" action="" >
<input type="text" name="foo[]" onkeyup="calc()" value="5"/>
<input type="text" name="foo[]" onkeyup="calc()" value="12"/>
<span id="totalCalc"></span>
</form>
​
js
var inputs = formNum["foo[]"];
var total = 1;
alert(inputs.length);
for (var i = 0; i < inputs.length; i++) {
total *= inputs[i].value;
}
alert(total);
working DEMO
I've figured out how to solve the problem. Just insert array after totalCalc, but not within totalCalc.
Thank you guys so much for helping me out :)

Why this javascript not enabling text boxes using check box?

Again in problem
Actually I have following jsp code in which I have few text boxes which I have made disabled by using property disabled="disabled".
Now problem is each record that I will get from database in each text box using iterator which iterates values added from databse in arraylist.If database return more than one record then using that check box I can enable textboxes but if databse resultset return only one record then I am unable to enable textboxes and throws following ERROR:
Message: 'document.f1.chk' is null or not an object
Line: 26
Char: 10
Code: 0
<script type="text/javascript">
function enable()
{
for(i=0;i<document.preapp.chk.length;i++)
{
if(document.preapp.chk[i].checked==true)
{
document.preapp.id[i].disabled=false;
document.preapp.vname[i].disabled=false;
document.preapp.comp[i].disabled=false;
document.preapp.cont[i].disabled=false;
document.preapp.wtm[i].disabled=false;
document.preapp.intime[i].disabled=false;
}
else
if(document.preapp.chk[i].checked==false)
{
document.preapp.id[i].disabled=true;
document.preapp.vname[i].disabled=true;
document.preapp.comp[i].disabled=true;
document.preapp.cont[i].disabled=true;
document.preapp.wtm[i].disabled=true;
document.preapp.intime[i].disabled=true;
}
}
}
</script>
<CENTER>Back to Search</CENTER>
<form method="post" action="" name="preapp">
<table border="1" align="center" width="100%">
<%
Iterator itr;
try
{
ArrayList al=(ArrayList)request.getAttribute("sq");
int i=0;
for(itr=al.iterator();itr.hasNext();)
{
i=i+1;
%>
<tr>
<td></td><td><input type="checkbox" name="chk" onclick="enable(this)" ></td></tr></tr>
<tr><td>Id</td><td><input type="text" name="id" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Visitor Name</td><td><input type="text" name="vname" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Comapny</td><td><input type="text" name="comp" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Contact</td><td><input type="text" name="cont" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Meeting Scheduled With</td><td><input type="text" name="wtm" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td>Entry Made On</td><td><input type="text" name="intime" value="<%=itr.next()%>" disabled="disabled" size="100%"></td></tr>
<tr><td></td>
</tr>
<tr>
</tr>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
%>
How Do solve this problem? please help me out!
It works like charm, except in the case you have only one TR block.
In that case, the .chk has no "length" attribute!
You should consider that case separately:
function enable()
{
if(document.preapp.chk.length == null)
{
disabledState = !document.preapp.chk.checked
document.preapp.id.disabled=disabledState;
document.preapp.vname.disabled=disabledState;
document.preapp.comp.disabled=disabledState;
document.preapp.cont.disabled=disabledState;
document.preapp.wtm.disabled=disabledState;
document.preapp.intime.disabled=disabledState;
} else {
for(i=0;i<document.preapp.chk.length;i++)
{
disabledState = !document.preapp.chk[i].checked
document.preapp.id[i].disabled=disabledState;
document.preapp.vname[i].disabled=disabledState;
document.preapp.comp[i].disabled=disabledState;
document.preapp.cont[i].disabled=disabledState;
document.preapp.wtm[i].disabled=disabledState;
document.preapp.intime[i].disabled=disabledState;
}
}
}
a couple of suggesions: instead of setting the properties of elements to true or false, try using the setAttribute and removeAttribute methods:
document.preapp.id[i].disabled=true;
//replace with:
document.preapp.id[i].setAttribute('disabled','disabled');
//to enable:
document.preapp.id[i].removeAttribute('disabled');
The way you're doing things works fine 99.9% of the time. I haven't seen the above code fail, though (I have had issues with the true/false approach).
Next: the error message you post, contains very useful information: check line 26 of your original code. 'document.f1.chk' is nowhere to be found in your snippet, so I can't check for typo's or other possible problems in your code there.
You're passing the element to the enable function, too. Why then, are you looping through all elements, checking all elems on the page?
function enable(elem)
{
var i = document.preapp.indexOf(elem);//
if (elem.checked === true)
{
document.preapp.id[i].removeAttribute('disabled');
//...
}
//functions have properties, exploit them:
if (typeof enable.previous === 'undefined' || enable.previous === i)
{
enable.previous = i;
return true;
}
document.preapp.id[enable.previous].setAttribute('disabled','disabled');
//...
enable.previous = i;
}
The last section of the enable function stores the index of the checkbox that was just clicked, so that when the enable function has been clicked before, there's no need to loop through all elements again: enable.previous holds the index of the checkbox that was clicked last time.
Lastly: there are no opening or closing bracket for the else block, and there is an extra line of whitespace. Else works fine without brackets, but only branches one line. In your code, this line is blank: either remove the else, or add brackets.
PS: Perhaps a fiddle would help to get a clear view of the situation?
As Teejay pointed out, in case of unique names, the elements are referenced directly, instead of a nodesList being passed.

Categories