i have been struggling with this for weeks n honestly i think Im going to go mad if i dont find a solution
ok i have a page with with a form which dymanically generates the input fields (checkboxes) whish is all done in PHP
what I need to do is count the different fields and alert the number of TICKED checkboxes. what i have so far is counting the number of dynamically generated checkboxes in each product but it wont count the checked fields, This i have been doing in Javascript.
<?
$sql="SELECT name FROM table WHERE type='product1'";
$result=mysql_query($sql);
// Show records by while loop.
while($myrow=mysql_fetch_array($result)){
?>
<input name="product1" type="checkbox" id="product1" value="<?php echo $myrow['name'];?> ">- <?php echo $myrow['name']; ?>
<br />
<?php
// End while loop.
}
?>
<script type="text/javascript">
function countBoxes(){
var c = 0;
var i = 1;
while((p = document.getElementById('product1'+i++))!=null)
if(p.checked)c++;
return c;
}
// Causes Warnings in NS browsers.
function warnCountBoxes(){
var c = 0;
p = export_form_data.product1;
for(var i=p.length-1;i>-1;i--){
if(p.item(i).checked)c++;
}
return c;
}
document.write("Number of meats available: "+export_form_data.product1.length+"<br>");
</script>
if anyone could help me alert the number of ticked checkboxes please i know that its this line that needs to be edited but cant figure out how to
i figured out the reason why it wont work but maybe I’m in the wrong form posting for this but i started posting here first and i dont want to double post
When my form is outputted to the mail it shows
meat = whatever is chosen
meat = whatever is chosen
and so on
what i need for it to count properly is
meat0 = whatever is chosen
meat1 = whatever is chosen
then it should be able to could properly
is there a way of changing the value of the array to add a number to this code
POSTing forms doesn’t submit the id, it submits the name of the element. I don’t think you want to alter the array member just to output a number. I have to assume that you are making a certain number of elements based on user input or on the number of available meats from a db, and you use a loop to make the input boxes. Maybe this is what you are looking for:
<?php
//assuming $_POST['number_of_meats'] is the number you are using to create checkboxes
for($i = 0; $i < $_POST['number_of_meats']; $i++)
{
echo '<input name="meat' . $i . '" type="checkbox" id="meat' . $i . '" value="' . $myrow['name'] . '" />- ' . $myrow['name'];
}
?>
Yes, there is a way, just add a condition in there to check the name, or id of your checkboxes (you could even pass that as a function parameter to make your code stay clean.
<script language="JavaScript">
function countCB( name )
{
var cb = document.getElementsByTagName("input");
var checked = 0;
for(i = 0; i < cb.length; i++)
{
if(cb*.type == 'checkbox' && cb*.checked && cb*.name == name)
{
++checked;
}
}
return checked;
}
alert(countCB('checkbox_name_value'));
</script>