Link to home
Start Free TrialLog in
Avatar of peter Ojeda
peter Ojeda

asked on

multiple selects

Hi experts I I am working on a scheduling web form that contains html and php to submit data to my sql server table. It consists of mostly select boxes that are populated from a database table. I want to be able to submit the selected values into my php. I will include a clip of the code below. Currently, If i have person 1 selected it submits, but if I select person 1 and person 2, it only submits person 2 and I receive an undefined index error for person 1.
pg1(form page)
<form id="fm1" name="crewa" method="post" action= "ce_crewa_manninginsert.php">
<div class="must">

<select id="PERSON1" name="PERSON1" onchange=" document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;
"  style="width: 150px;">
		<option value="">Select Employee</option>

		<?php 
			$serverName = "xxxx"; 

			$connectionInfo = array( "Database"=>"IS_DGMC");
			$conn = sqlsrv_connect( $serverName, $connectionInfo);

			if( $conn ) {
				// echo "Connection established.<br />";
			}else{
				 echo "Connection could not be established.<br />";
				 die( print_r( sqlsrv_errors(), true));
			}
			$location_query = "select distinct NAME from xxxx.dbo.CE_EMPLOYEES_CREW_A where POSITION = 'GENERAL' order by NAME";
			$locationQ = sqlsrv_query( $conn, $location_query );
			
			if( $locationQ === false) {
				die( print_r( sqlsrv_errors(), true) );
			}
			$i=0;
            $Lines[0] = '';
			while( $row = sqlsrv_fetch_array( $locationQ, SQLSRV_FETCH_ASSOC) ) {
				echo "<option value='".$row['NAME']."'>".$row['NAME']."</option>";
                $Lines[$i] = $row['NAME'];
                $i++;
			}
			$numLines = sizeof($Lines);
			sqlsrv_free_stmt($locationQ);
			
		?>
		</select>
  

<select id="PERSON2" name="PERSON2" onchange=" document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;
"  style="width: 150px;">
		<option value="">Select Employee</option>
		
		<?php $Employee = $row['Employee'];
		
			$serverName = "xxxxx"; 

			$connectionInfo = array( "Database"=>"IS_DGMC");
			$conn = sqlsrv_connect( $serverName, $connectionInfo);

			if( $conn ) {
				// echo "Connection established.<br />";
			}else{
				 echo "Connection could not be established.<br />";
				 die( print_r( sqlsrv_errors(), true));
			}
			$location_query = "select distinct NAME from xxx.dbo.CE_EMPLOYEES_CREW_A where POSITION = 'GENERAL' order by NAME";
			$locationQ = sqlsrv_query( $conn, $location_query );
			
			if( $locationQ === false) {
				die( print_r( sqlsrv_errors(), true) );
			}
			$i=0;
            $Lines[0] = '';
			while( $row = sqlsrv_fetch_array( $locationQ, SQLSRV_FETCH_ASSOC) ) {
				echo "<option value='".$row['NAME']."'>".$row['NAME']."</option>";
                $Lines[$i] = $row['NAME'];
                $i++;
			}
			$numLines = sizeof($Lines);
			sqlsrv_free_stmt($locationQ);
			
		?>
		</select>
<input type="submit" name="submit" value="Submit All" style="width: 150px; height:40px; margin-top: 1em; margin-left: 39%;">
</div>
</form>

Open in new window

pg2(insert page)
<?php

	
	ini_set('display_errors', 1);
	error_reporting(~0);

	$serverName = "xxxxx";
	$userName = "";
	$userPassword = '';
	$dbName = "xxxx";

	$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);

	$conn = sqlsrv_connect( $serverName, $connectionInfo);

	if( $conn === false ) {
		die( print_r( sqlsrv_errors(), true));
	}


//INSERT into database
	$sql = "INSERT INTO CE_MANNING_CREW_A (DATE, LINE1, PERSON1, PERSON2) VALUES (?, ?, ?, ? )";
	$params = array($_POST["DATE"],$_POST["Line1"],$_POST["PERSON1"],$_POST["PERSON2"]);
	
	

	$stmt = sqlsrv_query( $conn, $sql, $params);
	if( $stmt === false ) {
		 die( print_r( sqlsrv_errors(), true));
	}
	else
	{
		echo "";
	}

	sqlsrv_close($conn);
	if(isset($_POST['Submit']) )
{

  $errorMessage = "";
}
?>

Open in new window

Avatar of Peos John
Peos John
Flag of Malaysia image

You can submit the values as array as below

<select id="PERSON2" name="PERSON2[]" ....

just ad square bracket to the name of select control. Then the values will be posted as array.
Avatar of peter Ojeda
peter Ojeda

ASKER

hI Peos I tried putting the brackets on both of the select statements but still getting Notice: Undefined index: PERSON1
After some testing I found the error is in the script assocaiated with the dropdowns. I removed this script and it was able to submit both. I do need this script to work though for my project. The script disables a name if it was selected in a previous box. so if persona is selected in box 1, person a is disabled in box 2. Any suggestions on how I can fix this?
<script>
$(document).ready(function() {
  $('select').on('change', function() {
    var selected = $(this).val();
    var siblings = $(this).siblings('select');
    var siblingsSelected = [];
    $(siblings).each(function() {
      $(this).find('option:disabled').attr('disabled', false);
      if ($(this).val() !== "0") {
        siblingsSelected.push($(this).val());
      }
    });
    //disable option
    $(siblings).each(function() {
      var sib = $(this);
      $(this).find('option[value="' + selected + '"]').attr("disabled", true);
      $.each(siblingsSelected, function(index, value) {
        sib.find('option[value="' + value + '"]').attr("disabled", true);
      });
    });
  });
});

</script>

Open in new window

Can you inspect  the source on the browser and check how HTML code look like form?
I did and nothing looks wrong with it. It has something to do with the script i believe
You can use var_dump($_POST) in the PHP script to see the request variables.
Thanks Ray I did try that. On the first submission, I get the undefined error code when both boxes are inputted. I then click the back arrow and submit again without refreshing the page and both values are passed with no error. What do you think can be causing this?
greetings peter Ojeda , , ,  As I see in your javascript, the reason I think you are getting the -
     Notice: Undefined index: PERSON1
is because of this line -
      sib.find('option[value="' + value + '"]').attr("disabled", true);

when you change the second select, it looks to me it may change the current selected in PERSON1 to disabled? if the current selected is disabled then there is NO POST sent for that input NAME, because submit does not include the name of of a disabled.

I had difficultty wading through the javascript you have, and I am not sure about why you are using the  siblingsSelected array, It does not seem to FIT for what you need to do? ?

This seemed to be more strait forward programming with just raw javascript, the Jquery you have seems awkward to me and not efficient?
You have this -
     if ($(this).val() !== "0") {
but have no options with the value of "0" ? ? ?
you have raw javascript in the <selects> onchange attribute, which seems unusual in a JQuery thing.


here is my version of code that works in firefox -
span id="pick1">Pick One</span><br />
Selects -<br />
<form id="fm1" name="crewa">
<select id="PERSON1" name="PERSON1" style="width: 150px;">
<option value="0">Select Employee</option>
<option value="Mary Rose">Mary Rose</option>
<option value="Bob Kirt">Bob Kirt</option>
<option value="Fran Nore">Fran Nore</option>
<option value="Sam Jones">Sam Jones</option>
<option value="Bony Mora">Bony Mora</option>
</select>
<br /><br />
<span id="pick2">Pick One</span><br />
<select id="PERSON2" name="PERSON2" style="width: 150px;">
<option value="0">Select Employee</option>
<option value="Mary Rose">Mary Rose</option>
<option value="Bob Kirt">Bob Kirt</option>
<option value="Fran Nore">Fran Nore</option>
<option value="Sam Jones">Sam Jones</option>
<option value="Bony Mora">Bony Mora</option>
</select>
</form>


<script>
function id2el(elmt1){return document.getElementById(elmt1);}

id2el("PERSON1").onchange = id2el("PERSON2").onchange = function() {
  var sel = id2el("PERSON2");
  if(this.id == "PERSON2") {
  id2el("pick2").innerHTML = this.value;
  sel = id2el("PERSON1");
  } else id2el("pick1").innerHTML = this.value;
  if (this.value == sel.value) sel.selectedIndex = 0;
  var ops = sel.options;
  for (var i=1; i<ops.length; ++i) {
    if (ops[i].value == this.value)
      ops[i].disabled = true;
      else ops[i].disabled = false;
    }
  }
</script>

Open in new window

Hi Slick to be honest the JS I provided came from another post on here. I am relatively new to programming so I'm sure most things I do are not as efficient as they should be. I have tested your example. For the code I posted, if in select A I choose person 1, I am not able to choose that person in select B. Also I'm going to have to add multiple more select inputs.
You have some very confusing code in javascript you presented. It gets ANY and ALL selects for event 'change' with this -
        $('select').on('change', function() {

and then does the SAME exact thing in code for any select when it changes, both the first one as PERSON1   AND also the second one as PERSON2, , You said -
    "The script disables a name if it was selected in a previous box. so if persona is selected in box 1, person a is disabled in box 2"

so that if option selected in one select -  it should be disabled in the other select , which is what I did.
- - - - - - - - - -

Let's say there are 3 selects in use on the page - Can you tell me about the needed OPERATIONS you need for these selects on the page from Javascript, as the user picks a select option (person Name) in the top (first) select PERSON1 , and what needs to happen in the second PERSON2 select and what happens in the third select PERSON3? ?

And after the first select is picked, and the user changes to a name in the second select PERSON2 , what needs to happen in PERSON1 and what needs to happen in PERSON3 selects? ? ?
And maybe some info about why there should NOT be the same name in two selects as far as what is needed or restricted for the PHP SQL INSERT from the submit of these selects? ? ?
The idea of this project is to create a manning chart. So if person A is selected in select box 1, 2, or 3, it will be disabled in any other text box, making the user choose someone else. This is to remove the possibility of including somebody more than once. So if person A is selected in box 1, he cant be selected in box 2 or 3. And if person A is selected in box 1, and person B is selected in box 2, then only person C can be selected in box 3. The original JS worked for making the other names disabled once selected, but as mentioned above it removes the previous selected value.
I guess that I see what you need? But here is my attempt to do that -
Selects -<br />
<span id="sPERSON1">Pick One</span><br />
<form id="fm1" name="crewa">
<select id="PERSON1" name="PERSON1" style="width: 150px;">
<option value="0">Select Employee</option>
<option value="Mary Rose">Mary Rose</option>
<option value="Bob Kirt">Bob Kirt</option>
<option value="Fran Nore">Fran Nore</option>
<option value="Sam Jones">Sam Jones</option>
<option value="Bony Mora">Bony Mora</option>
<option value="Jim Smith">Jim Smith</option>
</select>
<br /><br />
<span id="sPERSON2">Pick One</span><br />
<select id="PERSON2" name="PERSON2" style="width: 150px;">
<option value="0">Select Employee</option>
<option value="Mary Rose">Mary Rose</option>
<option value="Bob Kirt">Bob Kirt</option>
<option value="Fran Nore">Fran Nore</option>
<option value="Sam Jones">Sam Jones</option>
<option value="Bony Mora">Bony Mora</option>
<option value="Jim Smith">Jim Smith</option>
</select>
<br /><br />
<span id="sPERSON3">Pick One</span><br />
<select id="PERSON3" name="PERSON3" style="width: 150px;">
<option value="0">Select Employee</option>
<option value="Mary Rose">Mary Rose</option>
<option value="Bob Kirt">Bob Kirt</option>
<option value="Fran Nore">Fran Nore</option>
<option value="Sam Jones">Sam Jones</option>
<option value="Bony Mora">Bony Mora</option>
<option value="Jim Smith">Jim Smith</option>
</select>
<br /><br />
<span id="sPERSON4">Pick One</span><br />
<select id="PERSON4" name="PERSON4" style="width: 150px;">
<option value="0">Select Employee</option>
<option value="Mary Rose">Mary Rose</option>
<option value="Bob Kirt">Bob Kirt</option>
<option value="Fran Nore">Fran Nore</option>
<option value="Sam Jones">Sam Jones</option>
<option value="Bony Mora">Bony Mora</option>
<option value="Jim Smith">Jim Smith</option>
</select>
</form>

<script>
function id2el(elmt1){return document.getElementById(elmt1);}

id2el("fm1").onchange = function(event) {

if (event.target.tagName.toUpperCase() == "SELECT") {
  id2el("s"+event.target.id).innerHTML = event.target.value;
  var sels = this.getElementsByTagName('select');
  var goo = 0;
  var oldIn = 0;
  for (var i =0; i< sels.length; ++i) {
    if (goo) {
      if (event.target.selectedIndex) {
        sels[i].options[event.target.selectedIndex].disabled = true;
        if (sels[i].selectedIndex == event.target.selectedIndex) {sels[i].oldIndex8 = 0; sels[i].selectedIndex = 0;}
	    }
      if(oldIn) sels[i].options[oldIn].disabled = false;
      }
    if(sels[i] == event.target) {goo=1; if(event.target.oldIndex8) oldIn = event.target.oldIndex8}
    }
  event.target.oldIndex8 = event.target.selectedIndex;
  }
}
</script>

Open in new window


You do NOT say anything about the user changing an Option after they pick it once, and set some below it than go Back and change to another? ? I just did what I thought would work.
Did not test this code in any but firefox, so it may not be robust and work in others?
Hi yes this is almost exactly it. The only trouble is that if it is out of order (select box 3 is picked first) then the other boxes don't have that name disabled. Going from box 1, 2, 3, to 4 works fine but if it was 4 to 3 to 2 to 1, the names do not appear disabled.
?????? What , did that I the first code run, where ANY select used would disable the choice in ALL other selects, , but you objected to that, and I changed it to the current ONLY selects BELOW the current choice are affective. The way you want it now can get to be very interference Cross-Linked if you have more than 3 or 4 selects, BECAUSE if you change a select when all have been filled in, then you not only have to disable the other selects option BUT I also have to ENABLE the old disabled select, and the more selects there are, then collisions can happen.
Sorry for the mix up and thank you very much. This appears to work perfect. Last question, in box 1 I selected persona and box B I selected person B. Then I selected person B i box A, but the span still showed person Bs' name. Is it possible for it to just go blank as to this will cause some confusion.
You are saying something about the <span> ? as - "but the span still showed person Bs' name" , ,
BUT I could not understand what you meant here -
   "in box 1 I selected persona and box B I selected person B. Then I selected person B i box A"

what do you mean by "box 1 I selected persona"  what is persona, , ,  I guess person A ?
But I do not understand the problem? You ask - "Is it possible for it to just go blank" - maybe, but what is the "it" you talk about? Is it the span -
     <span id="sPERSON2">Pick One</span>


this code changes the associated <span> -
       id2el("s"+event.target.id).innerHTML = event.target.value;
and does it every time.

I have this code -
      if (sels[j].selectedIndex == event.target.selectedIndex) {
         sels[j].oldIndex8 = 0; sels[j].selectedIndex = 0;
to RESET the select to the first option -
    <option value="0">Select Employee</option>
IF an UPPER select chooses a name that is USED in a lower select.

So maybe I don't understand, or the code does not work for you?
Not that I have much of an Idea what you are trying to do with this? ? ?, I changed the code to disable any and all other <option> in selects below and above the select you change. I think I have it so it can avoid collisions.

here is just the javascript, it used the SAME HTML as before with the -
      <select id="PERSON1" name="PERSON1" style="width: 150px;">

id2el("fm1").onchange = function(event) {
if (event.target.tagName.toUpperCase() == "SELECT") {
  id2el("s"+event.target.id).innerHTML = event.target.value;
  var oldIn = 0, sels = this.getElementsByTagName('select');
  if(event.target.oldIndex8) oldIn = event.target.oldIndex8;
  for (var i =0; i< sels.length; ++i) {
    if (event.target.selectedIndex && (sels[i] != event.target)) {
    sels[i].options[event.target.selectedIndex].disabled = true;
    if (sels[i].selectedIndex == event.target.selectedIndex) {sels[i].oldIndex8 = 0; sels[i].selectedIndex = 0;}
	}
    if(oldIn) sels[i].options[oldIn].disabled = false;
    }
  event.target.oldIndex8 = event.target.selectedIndex;
  }
}

Open in new window

This is what I am referring to. Fran Nore was selected in the first box. Then Bob Kurt was selected in the second box. I went back to box 1 and changed Fran Nore to Bob Kurt, but the Span element remained Bob Kurt, when the select box went back to select employee.User generated image
OK , thanks, , but in firefox it changes, when the index is changed in javascript, it triggers the event "onchange" in that select so the code as that event changes the <span> to 0

maybe this?
d2el("fm1").onchange = function(event) {

if (event.target.tagName.toUpperCase() == "SELECT") {
  id2el("s"+event.target.id).innerHTML = (target.selectedIndex ? event.target.value : "");
  var sels = this.getElementsByTagName('select');
  var goo = 0;
  var oldIn = 0;
  for (var i =0; i< sels.length; ++i) {
    if (goo) {
      if (event.target.selectedIndex) {
        sels[i].options[event.target.selectedIndex].disabled = true;
        if (sels[i].selectedIndex == event.target.selectedIndex) {
		id2el("s"+sels[i].id).innerHTML = "";
		sels[i].oldIndex8 = 0;
		sels[i].selectedIndex = 0;
		}
	    }
      if(oldIn) sels[i].options[oldIn].disabled = false;
      }
    if(sels[i] == event.target) {goo=1; if(event.target.oldIndex8) oldIn = event.target.oldIndex8}
    }
  event.target.oldIndex8 = event.target.selectedIndex;
  }
}

Open in new window

That did not seem to work. Sorry I should have included earlier that I was using google chrome.
ASKER CERTIFIED SOLUTION
Avatar of Member_2_248744
Member_2_248744
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You know what that is EXACTLY what I was looking for. Thank you very much sir you have been a great help and very patient through the whole process. This is why you are the "experts" and I am just a mere mortal. Once again thank you and have a great day.
Dude is a wizard. May be Bill Gates smurf account. No clue how he did this but I am forever grateful
ONE other thing, I used the  selectedIndex  instead of the search for the match in option for the value (name) because its faster than searching. BUT this REQUIRES that ALL, I mean ALL  selects have the same <options> listed, In the PHP this will be OK because you use the exact same SQL as -
    "select distinct NAME from xxxx.dbo.CE_EMPLOYEES_CREW_A where POSITION = 'GENERAL' order by NAME";

for both option lists in the selects, so I went ahead with the  selectedIndex for this... .

Just a note about the PHP, you do NOT need to do the second
    $locationQ = sqlsrv_query( $conn, $location_query );
because in the first   qlsrv_query( ) while loop you make an Array of names -
    $Lines[$i] = $row['NAME'];

so in the second and third and fourth select you can just run the $Lines array through, and fill all names in the options

for ($v=0;$v<count($Lines);++$v) {
    echo "<option>".$Lines[$v]."</option>";
// by default if the <option> has NO value attribute, it will use the Text of the <option> for its value
// so if the value and text are the same you can leave out the value thing
    }

Open in new window