Solved

Enable/Disable Checkboxes - Based on radio button selection

Posted on 2013-06-05
8
1,704 Views
Last Modified: 2013-06-11
Hello,

I've run into a bit of a dead end on a project I'm working on. I'm building a menu based ordering system using PHP/HTML/jQuery. Please see below for a complete description.

OBJECTIVE: The below code will dynamically display all menu items from a database as a radio button selection in a table. Within the description cell,
it will dynamically display all options that pertain to that specific item as checkboxes. I need only the checkboxes that pertain to the select item to
be active. If someone clicks on the radio button for item 1 it should uncheck (if checked) and disable all check boxes that pertain item 2, and if someone
checks the radio button for item 2, it should uncheck (if checked) and disable all check boxes that pertain to item 1. There will be more than 2 menu items
as time goes on, so it needs to follow the dynamics of the php.

Database:
Menu_Items
item_id      title                  description                                                      price
1            Value Meal 1      BBQ Chicken, corn, baked beans, and ice tea                  8.00
2            Value Meal 2      Hamburger, french fries, cole slaw, and ice tea            7.00

Menu_Options
option_id            item_id            title                              price
1                        1            Side Salad                  2.00
2                        1            Extra Baked Beans            1.00
3                        2            Cheese                        .50
4                        2            Bacon                        1.00

HTML/PHP Code:
<h3>Menu</h3>
<form action="menu.php" method="POST">
<table>
	<tr>
		<td>Select</td>
		<td>Name</td>
		<td>Description</td>
		<td>Price</td>
	</tr>
<?
	$item_result = mysql_query("SELECT * FROM `Menu_Items`");
	while($row = mysql_fetch_assoc($item_result))
	{
		$item_id		=	$row['item_id'];
		$option_result 	= 	mysql_query("SELECT * FROM `Menu_Options` WHERE `item_id` = '$item_id'");
		
		echo '	<tr>
					<td><input type="radio" name="menuitem" value="'.$row['item_id'].'"></td>
					<td>'.$row['title'].'</td>
					<td>'.$row['price'].'</td>
					<td>'.$row['description'].'<br/>
						<strong>Options: </strong><br/>';									
						while($opt_row = mysql_fetch_assoc($option_result))
						{
							echo 	'<input type="checkbox" name="option[]" value="'.$opt_row['option_id'].'"> '.$opt_row['title'].' $'.$opt_row['price'].'<br/>';
						}
		echo '			</td>
					</tr>';
	}

?>
	<tr>
		<td><input type="submit" value="Place Order" /></td>
	</tr>
</table>
</form>

Open in new window


JQUERY CODE: ???

I've considered changing the while loop to a for loop and using the increment variable, but I'm just not sure which direction on the jQuery side to go in. I've been banging my head against the wall on this for hours. Any help would be much appreciated.

Thanks,
Brian
0
Comment
Question by:bacamaro
  • 4
  • 2
  • 2
8 Comments
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 39222358
TLDR, and you might want to consider using the SSCCE model for asking questions like this one.  But that aside, I might be able to offer some help.  Please see this article and let me know if it's of any use.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_5450-Common-Sense-Examples-Using-Checkboxes-with-HTML-JavaScript-and-PHP.html

The use of radio buttons is to produce mutually-exclusive choices.  The use of checkboxes is to produce multiple choices.
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 200 total points
ID: 39222482
It depends on how you want this to work - if you change an option on the radio button then as I understand it you simply want to clear all the checkboxes which could be as simple as

$(function() {
  $(':radio').click(function() {
    $(':checkbox').attr('checked', false);
  });
});

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 39222500
Probably should have posted a link to this, too.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html

You could either toggle the visibility of some of the checkboxes when the radio button is fired or you could make an AJAX call and get an entirely new HTML document for the DIV that contained the menu options.  I would be inclined toward the latter, since it would give you a single point of impact when you wanted to change the burger options to include, say, lettuce or blue cheese.
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 200 total points
ID: 39222570
I would group the checkboxes within a div under the radio button. You then hide the div's with the checkboxes - when you click a radio button you clear the checkboxes, hide the visible ones and show the div with the checkboxes linked to the radio button clicked.

This should be fairly straight forward - code available if you wish to go this route.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Accepted Solution

by:
bacamaro earned 0 total points
ID: 39226626
Ray, I'm sorry the post was too long to read, my intention was to make sure all of the information was available to whoever cared to respond. I find it more helpful when I'm looking through posts if there isn't a lot of unnecessary banter in the thread because someone didn't post enough information in the first place. Thanks anyways for responding.

I didn't want to hide the checkboxes because someone may decide they want something different based on the options.

Julian, thanks for responding, you're post pointed me in the right general direction. The click function was the clue that allowed me to put it all together. That and some poking around stackoverflow. Thanks.

For those that stumble upon this question with the same problem, here is how I solved it:

I created a variable ($i) in php that would increment each time the loop ran. This allowed me to assign an id to the menu items (radio button) and a class to the options (checkboxes) that was unique to each run of the loop. I then had php spit out some jQuery based on those id's and classes each time the loop ran. This way each time you click a radio button (or anywhere on the screen for that matter) each jquery script would check to see if it's radio button was checked if it was it would enable the checkboxes in its class if not it would disable and uncheck them. Works like a champ.

Here's all the code:
<h3>Menu</h3>
<form action="menu.php" id="orderForm" method="POST">
<table>
     <tr>
          <td>Select</td>
          <td>Name</td>
          <td>Description</td>
          <td>Price</td>
     </tr>
<?
     $item_result = mysql_query("SELECT * FROM `Menu_Items`");
     $i=1;
     while($row = mysql_fetch_assoc($item_result))
     {
          $item_id		=	$row['item_id'];
          $menuid                =     'menuitem'.$i;
          $optionid               =     'optionitem'.$i;
	  $option_result 	= 	mysql_query("SELECT * FROM `Menu_Options` WHERE `item_id` = '$item_id'");

          echo "     <script>
                             $('#orderForm').click(function() {
			          if($('#".$menuid."').is(':checked')) {
			               $('.".$optionid."').removeAttr('disabled');
     			          }
			         else {
			              $('.".$optionid."').attr('disabled', true);
				      $('.".$optionid."').attr('checked', false);
                                  }
			     });</script> \r\n";     
		
          echo '	<tr>
	    		     <td><input type="radio" name="menuitem" value="'.$menuid.'"></td>
			     <td>'.$row['title'].'</td>
			     <td>'.$row['price'].'</td>
			     <td>'.$row['description'].'<br/>
			          <strong>Options</strong> <br/>';

  			          while($opt_row = mysql_fetch_assoc($option_result))
				  {
				        echo	'     <input type="checkbox" name="option[]" value="'.$optionid.'"> '.$opt_row['title'].' $'.$opt_row['price'].'<br/>';
				   }
		echo '          </td>
			      </tr>';
          $i++;
     }

?>
	<tr>
		<td><input type="submit" value="Place Order" /></td>
	</tr>
</table>
</form>

Open in new window


If you have questions, feel free to ask.

Brian
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39227314
Sorry - misread the request ignore this
0
 

Author Closing Comment

by:bacamaro
ID: 39237142
I select my own solution as the best because it lays out exactly what I did. Read the question, then read my last post and it should all come together for anyone having the same issue. Thanks to Ray and Julian for the assistance.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39237377
I have just re-read your post - this is not a good solution - you are dumping jquery code for every iteration of the loop!

The whole point of JQuery is to provide a powerful tool to be able to easily select elements in the DOM and manipulate them. Your solution does not make use of the power of JQuery and is effectively bloatware.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now