×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Unselected Listbox values

Unselected Listbox values

Unselected Listbox values

(OP)
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


RE: Unselected Listbox values

Hi

Nope, that unfortunately was not designed to be used like that. sad

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

Feherke.
feherke.github.io

RE: Unselected Listbox values

(OP)
Thanks for that reply - looks like I will have to start learning Javasript as well as starting PHP sad

RE: Unselected Listbox values

Hi

Quote (rogerte)

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: Javascript, if you need further assistance with the PHP part too, then better continue here. )

Feherke.
feherke.github.io

RE: Unselected Listbox values

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
https://www.doschke.name

RE: Unselected Listbox values

(OP)
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

RE: Unselected Listbox values

(OP)
Right her is an extract of my code

At the top (before the HTML tag

CODE --> 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 --> PHP)

<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 --> Javascript/Jquery

<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

RE: Unselected Listbox values

(OP)
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 --> JQuery

<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!

CODE --> 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");
} 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close