Solved

How to populate a table based on values selected from drop list which is inside HTML5 table

Posted on 2015-02-02
19
79 Views
Last Modified: 2015-02-14
Problem is : I have a dropdown list inside html5 table. The dropdown is well populated with the data. This dropdown is shown in the third column of the table. Now when the user selected an item in the drop down, the other details should get displayed in the next column in the same row. How will that be accomplished.  Pls help as i don't have in depth experience in PHP.  Following is my code :
<?php session_start(); ?>
<?php
	include ("dbcon.php");
	include("BrowserDetection.php"); 
	include("included_functions.php"); 
	if (empty($_SESSION['login_mail'])){
		header('Location: http://localhost/mainsite/');
	}
   else 
   {
  		//Pick username from user_dtls table based on $username
		$umailid = trim($_SESSION['login_mail']);
		if ($umailid == "Guest"){ $fullname = "Guest User"; }
		else {
			$pickname = "select u_name from user_dtls where u_emailid = '{$umailid}'";
			$result = mysqli_query($connection, $pickname);
			$resultarr = mysqli_fetch_array($result);
			if (!$resultarr)
			{ die("Database Query failed." . mysqli_error($connection)); }
			else {$fullname = $resultarr[0];}
			mysqli_free_result($result);
		}
   }
?>
<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<script src="js/modernizr.js"></script>
		<script src="js/jquery.min.js"></script>
		<script src="js/fabric.js"></script>
		<link rel="stylesheet" type="text/css" href="css/dsgncnv.css">
		
	</head>
	<body>
	    <hr style="float:left; margin-left:5%; margin-bottom:5px;" />
	    <hr style="float:left; margin-left:5%; width:90%;height:3px; background-color:#D2D2D3" />
	    <div class="cart-img"><img src="images/custmers.jpg" alt="" class="cartlineimg" /></div>
	    <hr style="float:left; margin-left:5%; width:90%;height:3px; background-color:#D2D2D3" />
		<div class="spc"></div>
		<div class="hdr-txt">
			<span class="spnid">SHOPPING CART</span>
		</div>
		<hr style="float:left; margin-left:5%; width:90%; height:1px; background-color:#D7D5D5; margin-bottom:5px" />
		<div class="disp_recs">
			<?php
				$var = trim($_SESSION['login_mail']);
				$query = "SELECT user_id FROM user_dtls where u_emailid = '{$var}'";
				$retrv = mysqli_query($connection, $query);
				$retrvarr = mysqli_fetch_array($retrv);
				if (!$retrvarr)
				{ die("Database Query failed." . mysqli_error($connection)); }
				else {$getid = $retrvarr[0];}

				//get details based on id
				$pickrecs = "SELECT DATE_FORMAT(tord_dt,'%d-%m-%Y') as label_date, file_path, file_name FROM utmp_orders where user_id = '{$getid}'";
				$result = mysqli_query($connection, $pickrecs); ?>
				<table id='display'>
					 <tr>
						<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Labels&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>
						<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creation Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>
						<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Labels&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>
						<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Total&nbsp;Price&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>
						<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>
					</tr>
					<?php while($resultarr = mysqli_fetch_assoc($result)){ ?>
					<tr>
					<td style="display:none;"></td>
					<td><img src="<?php echo $resultarr['file_path'] ?>" alt="" style="width:61px; height:54px" /></td>
					<td><?php echo $resultarr["label_date"] ?></td>
					<td><?php
							$pickrecs = "SELECT rt_qty, rt_cost FROM rate_mast order by rt_qty";
							$rtlist = mysqli_query($connection, $pickrecs); 
							echo "<select name='ratelist' value='' class='rdd'>";
							while($rtlistarr = mysqli_fetch_assoc($rtlist)){ 
								//echo "<option value = $rtlistarr[rt_qty]&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;$rtlistarr[rt_cost]>$rtlistarr[rt_qty]&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&pound;&nbsp;$rtlistarr[rt_cost]</option>";
								echo "<option value = $rtlistarr[rt_qty]>$rtlistarr[rt_qty]</option>";
							}
							echo "</select>";
					?></td>
					<td>
					    <?php //echo($rtlistarr[rt_cost]) ?>
							<input type="text" name="i-cost" value="" readonly class="icost">
					</td>					
					<td><a href=""><img src="images\cartidel.jpg" alt="" style="width:42px; height:42px"</a></td>					
				</tr>
				<?php } ?>
				</table>
				<?php mysqli_free_result($retrv);
				mysqli_free_result($result);
			?>
		</div>
	</body>
</html>
<?php
	mysqli_close($connection);
?>

Open in new window

0
Comment
Question by:Suneet Pant
  • 11
  • 7
19 Comments
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
Comment Utility
Assuming you want to populate your textbox with the rt_cost value relating to the rt_qty value, the easiest way to do it is to include the rt_cost value as a data attribute on the dropdown options, and then use jQuery to bind a change() event to the dropdown.

In your code above, build the <option> tags like this (note the data-cost attribute):

echo "<option value = $rtlistarr[rt_qty] data-cost='" . $rtlistarr[rt_cost] . "'>$rtlistarr[rt_qty]</option>";

Open in new window


And then add the following javascript to a SCRIPT tag in the HEAD of your document:

$(document).ready(function() {
   $("select[name='ratelist']").change(function() {
      var cost = $("option:selected", this).data('cost');
      $("input[name='i-cost']").val(cost);
   });
});

Open in new window

0
 

Author Comment

by:Suneet Pant
Comment Utility
Thanks Chris,  You really saved my day.

One more thing to ask - Here I am retrieving only one data on selecting an item from the dropdown. But what will be done in case I have to retrieve multiple data and display the records in different columns of the same row using ajax to avoid refreshing of the entire page. Pls help by
0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
Comment Utility
Hey Suneet,

When you build your <option> tags in PHP, you can include as many data attributes as you need:

echo "<option value = $rtlistarr[rt_qty] data-cost='" . $rtlistarr[rt_cost] . "' data-somevalue='" . $somevariable . "'>$rtlistarr[rt_qty]</option>";

Open in new window


And then extend your jQuery to put the values wherever you need them:

$(document).ready(function() {
   $("select[name='ratelist']").change(function() {
      var cost = $("option:selected", this).data('cost'); // get the value of the data-cost attribute
      var somevalue = $("option:selected", this).data('somevalue'); // get the value of the data-somevalue attribute
      $("input[name='i-cost']").val(cost); // set the i-cost input to the cost value
      $("input[name='i-somevalue']").val(somevalue); // set the i-somevalue input to the somevalue value
   });
});

Open in new window


Hope that makes sense, but come back if you need more info.
0
 

Author Comment

by:Suneet Pant
Comment Utility
Thank your very much Chris for help me. One last question. Where do I need to put this jQuery. I mean should I need to put under <head>....</head> or somewhere else.
0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
Comment Utility
Yeah - you normally put this stuff in the HEAD of your document, wrapped in a <script> tag:

<head>
   <title></title>
   <script src="js/modernizr.js"></script>
   <script src="js/jquery.min.js"></script>
   <script src="js/fabric.js"></script>
   <link rel="stylesheet" type="text/css" href="css/dsgncnv.css">
   <script type="text/javascript">
   $(document).ready(function() {
      $("select[name='ratelist']").change(function() {
         var cost = $("option:selected", this).data('cost');
         $("input[name='i-cost']").val(cost);
      });
   });
   </script>
</head>

Open in new window

0
 

Author Comment

by:Suneet Pant
Comment Utility
I actually put the jQuery within <head>....</head> tag. The code works fine. But one problem is coming. If I change item of first row dropdown ie "Labels", the value "Total Price" of the next column in the same row should get change. But instead value of all the rows  change which shouldnot happen.  Please Help
You can see in the image  below :
Pls check this
Here is the updated code :
<?php session_start(); ?>
<?php
	include ("dbcon.php");
	include("BrowserDetection.php"); 
	include("included_functions.php"); 
	if (empty($_SESSION['login_mail'])){
		header('Location: http://localhost/mainsite/');
	}
   else 
   {
  		//Pick username from user_dtls table based on $username
		$umailid = trim($_SESSION['login_mail']);
		if ($umailid == "Guest"){ $fullname = "Guest User"; }
		else {
			$pickname = "select u_name from user_dtls where u_emailid = '{$umailid}'";
			$result = mysqli_query($connection, $pickname);
			$resultarr = mysqli_fetch_array($result);
			if (!$resultarr)
			{ die("Database Query failed." . mysqli_error($connection)); }
			else {$fullname = $resultarr[0];}
			mysqli_free_result($result);
		}
   }
?>
<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<script src="js/modernizr.js"></script>
		<script src="js/jquery.min.js"></script>
		<script src="js/fabric.js"></script>
		<link rel="stylesheet" type="text/css" href="css/dsgncnv.css">
		<script>
		  $(document).ready(function() {
		  $("select[name='ratelist']").change(function() {
		      var cost = $("option:selected", this).data('cost');
		      $("input[name='i-cost']").val(cost);
		    });
		  });
		</script>
		
	</head>
	<body>

		<div class="hdr-txt">
			<span class="spnid">SHOPPING CART</span>
		</div>
		<hr style="float:left; margin-left:5%; width:90%; height:1px; background-color:#D7D5D5; margin-bottom:5px" />
		<div class="disp_recs">
			<?php
				$var = trim($_SESSION['login_mail']);
				$query = "SELECT user_id FROM user_dtls where u_emailid = '{$var}'";
				$retrv = mysqli_query($connection, $query);
				$retrvarr = mysqli_fetch_array($retrv);
				if (!$retrvarr)
				{ die("Database Query failed." . mysqli_error($connection)); }
				else {$getid = $retrvarr[0];}

				//get details based on id
				$pickrecs = "SELECT t_ordid, DATE_FORMAT(tord_dt,'%d-%m-%Y') as label_date, file_path, file_name FROM utmp_orders where user_id = '{$getid}'";
				$result = mysqli_query($connection, $pickrecs); ?>
				<table id='display'>
					 <tr>
						<th>Labels</th>
						<th>Creation&nbsp;Date</th>
						<th>Labels</th>
						<th>Total&nbsp;Price</th>
						<th>;</th>
					</tr>
					<?php while($resultarr = mysqli_fetch_assoc($result)){ ?>
					<tr>
					<td style="display:none;"></td>
					<td><img src="<?php echo $resultarr['file_path'] ?>" alt="" style="width:61px; height:54px" /></td>
					<td><?php echo $resultarr["label_date"] ?></td>
					<td><?php
							$pickrecs = "SELECT rt_qty, rt_cost FROM rate_mast order by rt_qty";
							$rtlist = mysqli_query($connection, $pickrecs); 
							echo "<select name='ratelist' value='' class='rdd'>";
							while($rtlistarr = mysqli_fetch_assoc($rtlist)){ 
                                                          echo "<option value = $rtlistarr[rt_qty] data-cost='" . $rtlistarr[rt_cost] . "'>$rtlistarr[rt_qty]</option>";	
                                                        }
							echo "</select>";
					?></td>
					<td>
					  <input type="text" name="i-cost" value="" readonly class="icost">
					</td>					
					<td><a href=""><img src="images\cartidel.jpg" alt="" style="width:42px; height:42px"</a></td>					
				</tr>
				<?php } ?>
				</table>
				<?php mysqli_free_result($retrv);
				mysqli_free_result($result);
			?>
		</div>
	</body>
</html>
<?php
	mysqli_close($connection);
?>

Open in new window

0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 500 total points
Comment Utility
Right. The reason that's happening is because we're setting 'i-cost' to the value of the dropdown, and there are lots of 'i-cost' inputs - they all get set. What we need to do here is to filter the i-cost to match the row (tr) that the <select> is in. We do this by getting the parent <tr> of the <select>, and then use that to set the value of the correct 'i-cost'

$("select[name='ratelist']").change(function() {
    var cost = $("option:selected", this).data('cost');
    var currentRow = $(this).parents('tr'); // get the <tr> that contains the changed <select>
    $("input[name='i-cost']", currentRow).val(cost); // set the value of 'i-cost' in the currentRow only
});

Open in new window

0
 

Author Comment

by:Suneet Pant
Comment Utility
Thank you very much Chris for helping me.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
No worries - glad I could help :)
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Suneet Pant
Comment Utility
hi chris I want one more help from you.
Pls check this link
Delete Records from html table
0
 

Author Comment

by:Suneet Pant
Comment Utility
Now please this time help me with the code as things are not coming in my mind how to do it. Lets say database table name is "cart", I want to update the contents of each row of the html table (as shown in the picture) to be saved in the "cart" table in one go using jquery and ajax. Rest of the code is same as above.
Please helpPic
0
 

Author Comment

by:Suneet Pant
Comment Utility
hi Chris pls help me
0
 

Author Comment

by:Suneet Pant
Comment Utility
Please reply
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
Hey Suneet,

You should really ask a new question for this as it's a different issue to the original question.
0
 

Author Comment

by:Suneet Pant
Comment Utility
ok i will do that
0
 

Author Comment

by:Suneet Pant
Comment Utility
I've requested that this question be deleted for the following reason:

se
0
 

Author Comment

by:Suneet Pant
Comment Utility
My Subscription has ended so I removing my question
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
The question was answered in full, so deleting it is not an option !! The OP should accept an answer.
0

Featured Post

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!

Join & Write a Comment

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

771 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

11 Experts available now in Live!

Get 1:1 Help Now