Jump to content

How determine which checkboxes are selected?


Dan06

Recommended Posts

I've created a dynamic form, which is made up of dynamically created check boxes. I'd like my javascript code to determine which of the check boxes in the form are selected. How can I do this? Suggestions/ideas are appreciated.

 

For radio buttons, since the name is the same I put together the following code:

var interval = document.forms[''].elements[''].length;
for (i=0; i<interval; i++){
	if(document.forms[''].elements[''][i].checked){
		var xyz = document.forms[''].elements[''][i].value;
	}
}

I tried to figure out how I could use the above with check boxes, but so far I've come up with nothing.

Link to comment
Share on other sites

How are the checkboxes named?

 

1. Are they named the same? If so then you can access all of them as an array.

 

2. Do they have same names with a unique id/number (name_1, name_2, etc)? If so, you can iterrate through them programatically.

 

3. Do they all have unique names? If so, then you want to create a javascript array with the server-side code that generates the checkboxes.

 

Please provide an example of your checkbox code.

 

 

Link to comment
Share on other sites

I've created a dynamic form, which is made up of dynamically created check boxes. I'd like my javascript code to determine which of the check boxes in the form are selected. How can I do this? Suggestions/ideas are appreciated.

 

For radio buttons, since the name is the same I put together the following code:

var interval = document.forms[''].elements[''].length;
for (i=0; i<interval; i++){
	if(document.forms[''].elements[''][i].checked){
		var xyz = document.forms[''].elements[''][i].value;
	}
}

I tried to figure out how I could use the above with check boxes, but so far I've come up with nothing.

 

Hmm...you don't name your forms or form elements?  It's kind of strange reading a bunch of form references with empty strings as their names.

 

In any event, since multiple checkboxes can be checked, you'll need to come up with an array to store the info.  Something like:

 

var checkboxRange = document.forms[''].elements[''].length;
var formElems = document.forms[''].elements['']; //save typing and make code more efficient and readable
var results = new Array();

for(var i = 0; i < checkboxRange; i++)
{
   if(formElems[i].type == "checkbox" && formElems[i].checked)
   {
      results.push(formElems[i].value);
   }
}

Link to comment
Share on other sites

The check boxes have unique names and unique ids, however, with respect to each check box the name is the same as the id. The php code for the form is below:

 

<?php
echo '<form name="categoryRegister" id="categoryRegister" method="post" onsubmit="return categoryRegistration()">
<table width="600" border="0" cellpadding="10" cellspacing="0">
<tr>
    <td>';
        while($domesticRow = msql_fetch_assoc($domesticGoodsResult)){
            echo '<center><input type="checkbox" name= ' . $domesticRow['categoryName'] . ' id=' . $domesticRow['categoryName']  . ' value=' . $domesticRow['categoryName'] . ' />' . $domesticRow['categoryName'] . '</center><br/>';
        }
    echo '</td>
    <td>';
        while($interRow = msql_fetch_assoc($internationalGoodsResult)){
             echo '<center><input type="checkbox" name= ' . $interRow['categoryName'] . ' id=' . $interRow['categoryName']  . ' value=' . $interRrow['categoryName'] . ' />' . $interRrow['categoryName'] . '</center><br/>';
        }
echo '
    </td>
</tr>
<tr>
    <td colspan="2"><center><input type="submit" name="submit" value="Sign-Up"/></center>
    <input type="hidden" name="type" value="goodsInfo" />
    </td>';
?>

 

I do name my forms and their elements, however, in my example code I removed their names. My intent was to give a general example of something I had used with radio buttons in another form.

Link to comment
Share on other sites

If you want a list of ALL the checkboxes checked in a form, Nightslyr's method should work fine. However, if you only need the checkboxes for a specific group of checkboxes you could either have the server-side script create a JS array of the field to iterrate through or you could put them all in a div and then iterrate through the div's child elements - similar to Nightslyr's approach (but for a div instead of a form). Since you have two TDs with sets of checkboxes you may want to have results for each TD independantly. In that case follow the same approach Nightslyr presented for the form, but do it for each child elment for the TDs (you would want to give each an ID). But I don't know about your intended goal to know if that's what you want.

Link to comment
Share on other sites

I'm unclear on one aspect of Nightslyr's method, particularly, the .element[] component of the code.

 

The form name is "categoryRegister" - so, the js should look like:

var formElems = document.forms['categoryRegister'].elements['???'] 

 

But name do I give for the element, since the check boxes all have unique names/ids?

 

Link to comment
Share on other sites

I'm unclear on one aspect of Nightslyr's method, particularly, the .element[] component of the code.

 

The form name is "categoryRegister" - so, the js should look like:

var formElems = document.forms['categoryRegister'].elements['???'] 

 

But name do I give for the element, since the check boxes all have unique names/ids?

 

 

Sorry, I wrote that in a rush.  I believe it should be:

 

var formElems = document.forms['categoryRegister'].elements;

 

That should assign all of the categoryRegister's fields to the formElems variable as an array.  Then you can just iterate through all of them with the for-loop I wrote earlier.

 

Keep in mind, my solution doesn't keep track of which checkbox was checked (if any).  It merely stores all checked values in an array for you to use elsewhere.  If you need to keep track of which checkbox(es) were accessed, you'll need to create an associative array, something along the lines of:

 

for(var i = 0; i < checkboxRange; i++)
{
   if(formElems[i].type == "checkbox" && formElems[i].checked)
   {
      results[formElems[i].name] = formElems[i].value;
   }
}

 

Then you could output it like so:

 

for(var key in results)
{
   alert("Element " + key + " checked.  Its value is: " + results[key]);
}

Link to comment
Share on other sites

Nightslyr, thanks for the clarification on the .elements component of the code as well as on how to keep track of which check box(es) are accessed.

 

My goal was to have javascript determine which check boxes were selected and return those values to a processing php page, so they could be inserted into a db. Your code and explanations has helped me understand how to accomplish that goal.

Link to comment
Share on other sites

My goal was to have javascript determine which check boxes were selected and return those values to a processing php page, so they could be inserted into a db. Your code and explanations has helped me understand how to accomplish that goal.

 

Are you doing this through AJAX? If not, there is absolutely no reason for JavaScript here since the checkbox values will be available when the form is posted to the PHP processing page. In fact, I don't know how you would use this if not using AJAX.

Link to comment
Share on other sites

Well, the goal is to use AJAX... I can't get php to convert the resultant array into a string via implode()...  I'm not sure if the problem is in the js or php code. I get the error message: 

Warning: implode() [function.implode]: Invalid arguments passed

I've put my js & php code below. If anyone has any suggestions/ideas, let me know. Thanks.

 

var formElements = document.forms['categoryRegister'].elements;
var elementsRange = formElements.length;
var checkedResults = [];
for (i=0; i<elementsRange; i++){
	if (formElements[i].type == "checkbox" && formElements[i].checked){
		checkedResults = formElements[i].value;
	}
}

 

 

$categoryListingArray = $_POST['checkedResults'];
$categoryListing = implode(',' , $categoryListingArray);

$updateQuery = sprintf("UPDATE goods SET categoryListing=%s WHERE Id=" . "'" . $_SESSION['registrationId'] . "'",  
$format->formatValue($categoryListing));

 

 

Link to comment
Share on other sites

Well, I can't see all of your code, but unless you are POSTing the values through AJAX with multiple fields then it will not be received as an array. I suggest you post the values as a delimited string. Then in PHP explode() the values and then iterrate through each one for validation. Then implode the valid values back into the format you need them for the query:

 

var formElements = document.forms['categoryRegister'].elements;
var elementsRange = formElements.length;
var checkedResults = [];
for (i=0; i<elementsRange; i++){
if (formElements[i].type == "checkbox" && formElements[i].checked){
	checkedResults = formElements[i].value;
}
}
//Create a string with all values delimited by a |
resultsList = checkedResults.join('|');

 

$categoryList = $_POST['checkedResults'];
$categoryListArray = explode('|', $_POST['checkedResults']);

foreach ($categoryListArray as $listValue)
{
    //Validate/process each list item
    //Remove invalid items
}
$categoryListing = implode(',' , $categoryListArray);

Link to comment
Share on other sites

Thanks mjdamato and Nightslyr for your help with the code. Unfortunately, there seems to be problems with my js code. There was a problem with my php code, which I was able to fix by changing the dynamic checkbox names from being unique for each one to a checkbox array. That solved the php side issues... When using only php code I'm able to determine which checkboxes are selected and have them put into a string and then inserted into a table. However, when I try the js code to determine which checkboxes are selected and put them into a string, no checkbox values are gathered and inserted into a string, even though multiple checkboxes are selected. Below is the php and js code I'm using, if someone knows how to or has any suggestions to fix my problem please let me know.

 

echo '<form name="categoryRegister" id="categoryRegister" method="post" onsubmit="return categoryRegistration()">
<table width="400" border="1" cellpadding="10" cellspacing="0">
<tr>
<td>';
    	while($productRow = mysql_fetch_assoc($productCategoriesResult)){
	echo '<center><input type="checkbox" name="categoryCheckbox[]" id="' . $productRow['categoryName']  . '" value="' . $productRow['categoryName'] . '" />' . $productRow['categoryName'] . '</center><br/>';
	}
echo '
    </td>
<td>';
    	while($serviceRow = mysql_fetch_assoc($serviceCategoriesResult)){
	echo '<center><input type="checkbox" name="categoryCheckbox[]" id="' . $serviceRow['categoryName'] . '" value="' . $serviceRow['categoryName'] . '" />' . $serviceRow['categoryName'] . '</center><br/>';
	}
echo '
    </td>
</tr>
<tr>
<td colspan="2"><center><input type="submit" name="save" value="Save"/></center>
    <input type="hidden" name="type" value="categoryRegistration" />
    </td>
</tr>
</table>
</form>';

 

var checkboxElements = document.forms['categoryRegister'].elements['categoryCheckbox[]'];
var elementsRange = checkboxElements.length;
var checkedResults = [];
for (i=0; i<elementsRange; i++){
	if (checkboxElements[i].checked){
		checkedResults = checkboxElements[i].value;
	}
}
var resultsList = checkedResults.join(',');

var type = document.forms['categoryRegister'].elements['type'].value;

var params = "resultsList=" + resultsList + "&type=" + type;

Link to comment
Share on other sites

My previous post's answer is not completely correct. It does work, but will also collect unselected check boxes' empty values in the desired array. The better way to do it is

checkedResults.push(checkboxElements[i].value);

 

I incorrectly thought js, like php, allowed you to add to the end of an array with:

 

checkedResults[] = checkboxElements[i].value;

 

 

Link to comment
Share on other sites

My previous post's answer is not completely correct. It does work, but will also collect unselected check boxes' empty values in the desired array. The better way to do it is

checkedResults.push(checkboxElements[i].value);

 

I incorrectly thought js, like php, allowed you to add to the end of an array with:

 

checkedResults[] = checkboxElements[i].value;

 

Yeah, JavaScript has just enough minute differences in syntax from PHP to make a person want to rip their hair out at times.

 

I haven't had the time to read through all of the code you wrote a few posts ago, but the best way to get a hold of a group of checkboxes that you're passing to PHP as an array in JS is to do the following:

 

var myBoxes = document.forms["myForm"].elements["boxGroup1[]"];

 

That will assign all the checkboxes with the name boxGroup1 as an array in the myBoxes variable (see: http://www.javascripttoolbox.com/bestpractices/#squarebracket).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.