Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unselected Listbox values

Status
Not open for further replies.

rogerte

Programmer
Nov 9, 2001
164
GB
Another newbie question!

I know you can get the option value of selected items in a listbox from the $_POST variable, but is it possible to determine all items in a listbox (selected and unselected) following a post submit.

What I am trying to achieve is:
A form has 2 listboxes. By selecting a name in listbox1 it is transferred to listbox2. When the selection of names is finished clicking on a SAVE button will allow the option values of all the items in listbox2 to be saved to a data table without having to select all the items in listbox2 before clicking on the SAVE button.

Many thanks


 
Hi

Nope, that unfortunately was not designed to be used like that. :-(

In various projects I worked with 2 workarounds :
[ol]
[li]listbox2 has [tt]multiple[/tt] attribute set and [tt]onsubmit[/tt] a script selects all options[/li]
[li]use an additional [tt]hidden[/tt] input and [tt]onsubmit[/tt] a script copies all options' values as comma ( or whatever matches your data ) separated enumeration to the input[/li]
[/ol]
Personally I find the 1[sup]st[/sup] one messy so I prefer the 2[sup]nd[/sup] one.


Feherke.
feherke.github.io
 
Thanks for that reply - looks like I will have to start learning Javasript as well as starting PHP [sad]
 
Hi

rogerte said:
By selecting a name in listbox1 it is transferred to listbox2.
I guess you already have some JavaScript there. If you post it, we can suggest a solution that plays nice with your current code. ( Although this part would belong to forum216, if you need further assistance with the PHP part too, then better continue here. )


Feherke.
feherke.github.io
 
You're involved with HTML anyway, so yes, it's harder to learn separately. There are courses doing that, but they are almost always unsatisfying when you don't get real-world issues taught.

That said you could choose checkboxed items and name all of them with name="arrayname[]", that'll arrive in PHP as $_POST['arrayname'] as an array, which means checked choices arrive in $_POST['arrayname'].

It's then an advanced job to create a widget that instead of displaying checkbox items displays two lists of choices and selections based on the checked status and vice versa by their usage also manipulate these form elements, which are the real deal inputs later sent to the backend. And that's even more advanced Javascript and CSS, most likely. But you may live with that kind of interface as long as you want to concentrate on learning the PHP side and simply rely on the fact it's possible to return an array of values from an HTML form, which is indeed possible.

What's perhaps most advisable would be learning a bit of jQuery as far as being able to override the normal HTML form submit with an event handler function using ajax to submit the form. You'll learn something useful in any case and gain more control about how the data of the HTML inputs are put together for your PHP side code as GET or POST request.

Plus you get an understanding about the HTTP protocol, which you should actually also have as a basis of how this all comes together anyway, and why the PHP side variables are called $_GET and $_POST at all.

Bye, Olaf.

Olaf Doschke Software Engineering
 
Apologies for not replying sooner, have been away for a few days with no access to the internet.

I will be back in the real world soon, and will upload a synopsis of what I have done so far.

Basically I am using some JQuery I found online to control the 2 listboxes and the buttons that move items between them. I must admit I don't understand how it works yet - but that side works great!

I have tried a JQuery function that is supposed to select all items in the listbox whose id is passed to it, but it seems to select all items in both listboxes, but I have been unable to program PHP code to extract the selected line item ids, which is what I need to do. I wonder if I am getting the select id and name mixed up.

I have been wondering if a better option was to have a hidden input, with a Javascript/JQuery function thast is triggered when the submit button is clicked that gets all the lineitem ids from the required listbox, add them as an array to the input, which I assume must have an id (or name?) like "hidden[]" and then in the PHP code explode the array to get the individual ids that are then written out to the table.

Just need to work out how to do this.

Thanks

Roger
 
Right her is an extract of my code

At the top (before the HTML tag
PHP:
<?php
	require_once 'session.php';
	
	require_once 'conn.php';
	/* Code to get username to display on HTML page */
	$acc_query = $conn->query("SELECT * FROM `admin` WHERE `admin_id` = '$_SESSION[admin_id]'") or die(mysqli_error($conn));
	$acc_fetch = $acc_query->fetch_array();
	$acc_name = $acc_fetch['username'];


if (isset($_GET["class_id"])) {
  // First get class description to display on form AND class_id 
  $c_query = $conn->query("SELECT * FROM `classdetails` WHERE `class_id`= '$_REQUEST[class_id]'") or die(mysqli_error($conn));
	$c_fetch = $c_query->fetch_array();
	$class = $c_fetch['class_id'];
  $class_name = $c_fetch['class_name'];
	
	// Now get list of members NOT in class - used to fill the left listbox (name="from[]" id="search")
	$g_query1 = $conn->query('SELECT * FROM memberdetails WHERE mem_id NOT IN (SELECT mem_id FROM memberdetails WHERE mem_id in (select mem_id from classmember where class_id= '.$class.')) ORDER BY firstname, lastname ASC') or die(mysqli_error($conn));
	
	// Finally Get list of memebers in selected class - used to fill right listbox (name="to[]" id="search_to")
  $g_query2 = $conn->query('SELECT * FROM memberdetails WHERE mem_id IN (SELECT mem_id FROM memberdetails WHERE mem_id in (select mem_id from classmember where class_id= '.$class.')) ORDER BY firstname, lastname ASC') or die(mysqli_error($conn));
	}


// Process after the submit button clicked
if ($_SERVER["REQUEST_METHOD"] == "POST") {


        // 1. delete existing records for the required class
	// 2. now add all records from second listbox by exploding hidden text
	header("location: home.php");
}
	
?>

The Form part of the body
Code:
<div class="row">
	<form class="form-horizontal" method = "POST" action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">  

				<div class="col-xs-5">
				  <h2 style="text-align:center">Available members</h2>
                                  <select name="from[]" id="search" class="form-control" size="24" multiple="multiple">
                                  <?php
	                           // get array of all club members not in required class
                                     while($g_fetch = $g_query1->fetch_array()){
                                       echo "<option value = ".$g_fetch['mem_id'].">".$g_fetch['firstname'].' '.$g_fetch['lastname']."          </option>";
                                     }
				  ?> 
				  </select>
				</div> <!-- col-xs-5 -->
				
				<div class="col-xs-2">
					<br /><br /><br /><br /><br /><br /><br /><br /><br />
                                        <button type="button" id="search_rightSelected" class="btn btn-info btn-block"><i class="glyphicon glyphicon-chevron-right"></i></button>
                                        <button type="button" id="search_leftSelected" class="btn btn-info btn-block"><i class="glyphicon glyphicon-chevron-left"></i></button>
			
					<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
					<button type="submit" name="save" id= "save" class="btn btn-primary btn-block"><span class = "glyphicon glyphicon-save"></span> Save Changes</button>

				</div> <!-- col-xs-2 -->
				
				<div class="col-xs-5">
				  <h2 style="text-align:center"><?php echo $class_name?> members</h2>
                                  <select name="to[]" id="search_to" class="form-control" size="24" multiple="multiple">
                                  <?php
	                           // get initial array of members in class
                                   while($g_fetch = $g_query2->fetch_array()){
                                     echo "<option value = ".$g_fetch['mem_id'].">".$g_fetch['firstname'].' '.$g_fetch['lastname']."          </option>";
                                   }
				  ?> 
                                  <input type="hidden" id="idlist" name="idlist">
				  </select> <!-- col-xs-5 -->
				</div>
  </form>			
			
			
			
</div> <!-- row -->

Below the </body> tag is the following Javascript

Code:
<script type="text/javascript" src="../jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../js/multiselect.min.js"></script>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#search').multiselect({
            search: {
                left: '<input type="text" name="q" class="form-control" placeholder="Search..." />',
                right: '<input type="text" name="q" class="form-control" placeholder="Search..." />',
            },
            fireSearch: function(value) {
                return value.length > 3;
            }
        });
    });
    </script>

What I have been trying to do is:
1) In the form include a hidden text input
2) Create an onselect script to extract all the IDs of the second selects options as comma separated variable that is then written to the hidden text.
3) In the $_POST of the PHP section:
Delete all existing records for the selected class
Explode the array in the Hidden input
For each mem_ID insert the class_id and mem_id into the table.

If I manually write the data to the hidden input I can get the PHP side to work ok. i.e. If I used value="1104,1328,787,1002" whthe Table would end up with records for those 4 values.

It's the onselect script and inserting it into the hidden input I am having problems with.

Cheers

Roger

 
I finally sorted it by combining code I found on the web. Probably not the most efficient code, but it works!

Function to create string of all items in listbox:
Code:
<script>
$(document).ready(function() 
{
    $("#submit1").click(function()
    {
        $("#form1").submit(function()
        {
           
           var options = $('[name="to[]"] option');

           var result = $.map(options ,function(option) {
           return option.value;});

	   $("input:text").val(result);

           $( "#form1" ).submit();
           return false;
        });
    });  //submit

});  //ready

and the PHP code in the page that does the work!
PHP:
<?php

require_once 'session.php';
	
require_once 'conn.php';
  
if( isset($_REQUEST["memids"] )) {

   $class = $_SESSION['classid']; 
	 
   // 1. delete existing records for the required classid
   $conn->query("DELETE FROM classmember WHERE class_id = $class")  or die(mysqli_error($conn)); 

   // 2. now add all records from second listbox

   $text = $_REQUEST["memids"];

   $memidArray = explode(",",$text);

   foreach ($memidArray as $memid) {
       $conn->query( "INSERT INTO classmember (class_id, mem_id) VALUES ($class, $memid)")  or die(mysqli_error($conn));
	  }	
   header("location: home.php"); }
 else {
   header("location: Club.php");
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top