EDIT : PLEASE FIND MY SOLUTION BELLOW
I have two select boxes in a FORM that i populate from two different tables.
SELECT1 displays client specific options.
SELECT2 displays all available options except those already on SELECT1
Everything works fine populating them, moving items from one to the other etc.
What I don't have a clue is how to, after submit of the FORM, I store those items of SELECT1 back to the database.
For each item on that SELECT box I need to check if it already exists on MY_TABLE_2 and if it does not, store it.
When I check var_dump(SELECT1) I only see the value of the last selected item but it normally contains more than one item in SELECT1.
For now I'm calling a stored procedure for all the other fields that will go on MY_TABLE_1 and that is OK.
I would need to do some transaction that updates the two tables or rolls back if i get an error. That is working if i store only one item.
But how I send to the stored procedure ALL the items.
Any help or clues?
Here's a print-screen if it can help understand:
The code to generate the form:
echo '<select name="ed_clilabelcodes" id="ed_clilabelcodes" style="width: 200px" multiple>';
while($row = sqlsrv_fetch_array($dvclilablist)){
echo '<option value="'.$row[0].'">'.$row[0].' - '.$row[1].'</option>';
}
echo '</select>';
----------- MY SOLUTION -----------
All items on any of those select boxes exist in a table (dbo.MyItems) identified by the field OptCode.
What I really needed was to store witch of those items were selected by a particular client.
I was thinking of having a second table where I would store those items but I was in reality duplicating information and I didn't find it to be the best solution.
Since I really only needed those selected codes attached to the client file I did the following:
I have one javascript function inspired from HERE that allows me to move items between the two select boxes and, by the way, from HERE to create a function that sorts the items in the boxes.
Each time I add or remove an item from the client's list box I immediately call the sort function, so I just update a hidden input value with all item values (codes) present in the select box immediately calling this javascript function :
function RecheckCodes() {
var vlist = document.getElementById("ed_clilabelcodes");
var vlabcodes = "";
var i;
for (i = 0; i < vlist.length; i++) {
if (i == 0) {
vlabcodes = vlabcodes + "\'" + vlist.options[i].value + "\'";
}
else {
vlabcodes = vlabcodes + ",\'" + vlist.options[i].value + "\'";
}
}
document.getElementById("v_clilabcodes").value = vlabcodes;
}
On FORM Post i just save that string in a client field.
Latter i can repopulate the boxes for edit using following 2 stored procedures to get the items (first SQL will get the string with the codes and is called from the 2nd one that gets the item description from items table).
ALTER PROCEDURE [dbo].[DavGetOptCodeByClient]
#vclicode nvarchar(12),
#vopttype nvarchar(12),
#voptcodes nvarchar(300) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #voptcodes = optcodes
FROM dbo.dav_client_options
WHERE clinumber = #vclicode AND opttype = #vopttype
END
ALTER PROCEDURE [dbo].[DavGetOptDetailByClient]
#vclicode nvarchar(12),
#vopttype nvarchar(12)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #v2optcodes nvarchar(1000)
DECLARE #vsql nvarchar(1000)
exec dbo.DavGetOptCodeByClient #vclicode,#vopttype, #v2optcodes OUTPUT
SET #vsql = 'SELECT optcode, optdetail ' +
'FROM dbo.dav_global_options ' +
'WHERE ("optcode" IN ('+#v2optcodes+')) AND (opttype = '''+#vopttype+''')'
EXEC sp_executesql #vsql
END
So everything is working fine for what I needed even if I'm sure some improvement can be made on the code.
to be able to send all the elements the simplest option is to select them, it is not enough that they are in the list but they have to be selected, for that it must be activated the "multiple" option of the select, once done that by pressing the key "control" or "shift" you can make multiple select in your list.
<form action="#" method="post">
<select name="Color[]" multiple> <!--the option multiple must be active and be array -->
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" value="Get Selected Values" />
</form>
Another option is to add this small javascript (jQuery) in an html so you do not have to press or control or shift when you select several options, just click and you will be selected
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
Source :How to avoid the need for ctrl-click in a multi-select box using Javascript?
And at the end you have your data with a simple php
<?php
$data=$_POST;
if($data) {
foreach ($data['Color'] as $option) {
echo $option;
}
var_dump($data);
}
?>
Related
I have two drop downs, one is repositories list where lists not get from database
another one drop down is their branchs
if I select "a" repo option another drop down should show their branches and user change his mind select "b" option second drop down should show their branches
how can done this using php without using database ?
If I understand your question properly, you want to create something like this:
I assume that you are aware of all consequences from not using DB for this, so I skip this part.
You will have to use some Javascript, and to make it easier - jQuery, that makes two things:
Shows the second dropdown after user selects an option from the first one,
Updates options in 2nd dropdown when value of the 1st dropdown changes.
So here's your HTML:
<select id='dropdown1' name='branch'>
<option value='it'>IT</option>
<option value='entertainment'>Entertainment</option>
</select>
<select id='dropdown2' name='branch-sub' style='display:none;'></select>
And here's your jQuery / javascript:
var options = {
'it': ["Programming", "Software", "Hardware", "..."],
'entertainment': ["PC Games", "Movies", "Music", "..."]
// And so on
}
$(document).ready(function(){
$('#dropdown1').change(function(){
$('#dropdown2').show();
$('#dropdown2').html('');
var opts = options[$('#dropdown1').val()];
for(var a = 0; a < opts.length; a++)
$('#dropdown2').append("<option value='" + opts[a] + "'>" + opts[a] + "</option>");
});
});
Edit (15-03-2018): I updated the JS code, so it's working now.
I have a form to insert data into a MySQL table that uses two drop down menus. The first is a list of parks and the second a list of rides. The second drop down box should only display items linked to the first by the column 'park_id'. I need a simple way for the second box to populate based on the first's selection.
This is the form so far:
<tr><td>Select Park:</td>
<td><select name="park_id">
<option value="">Select Park</option>
<?php foreach ($res as $row) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row['park_id'], $row['name'] );
} ?>
</select></td></tr>
<tr><td>Select Ride:</td>
<td><select name="ride_id">
<option value="">Select Ride</option>
<?php foreach ($res2 as $row2) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row2['ride_id'], $row2['name'] );
} ?>
</select></td></tr>
So somehow a query needs to run after selecting a park and use '$park_id = $row[park_id]' to help generate the results for the 'Select Ride' dropdown.
This is the query I need to use for the second drop down:
$qry2 = "SELECT ride_id, name FROM tpf_rides WHERE park_id = $park_id ORDER BY name ASC";
Can anyone talk me through this? Also my skill are very limited so a relatively simple solution would be great.
Thanksark
For this you will have to get into AJAX, and I highly recommend using jQuery's implementation. You will also need to get a good grip on JSON string coding and decoding.
The basic Idea of your code will be like so:
// listen for user to change the <select> item
$('select#park').on('change', function(){
$.ajax({
url: 'getrides.php' // send a park id to this script
,cache: false // do not cache results in browser
,type: 'POST' // send POST to getrides.php
,data: {'park_id': $('select#park').val()} // getrides.php will receive $_POST['park_id']
,dataType: 'json' // this AJAX call expects a JSON string as a return value
,success: function(data){ // the data variable will be converted to an array from JSON
// check out all your data
console.log(data);
// loop through your array
$.each(data, function(index, info){
// see your array indexes
console.log(index);
// see data in each array item
console.log(info);
});
}
});
UPDATE
You can also load all of the parks and rides into a Javascript array and based on what the user chooses from the dropdown then populate the second dropdown with those array members.
<script>
var rides = new Array();
rides['park1'].push('ride1');
rides['park1'].push('ride2');
rides['park1'].push('ride3');
rides['park1'].push('ride4');
rides['park1'].push('ride5');
rides['park2'].push('ride1');
rides['park2'].push('ride2');
rides['park2'].push('ride3');
rides['park2'].push('ride4');
rides['park2'].push('ride5');
// listen for user to change the <select> item
$('select#park').on('change', function(){
// clear current DD options
$('select#rides').html();
// loop through array of available rides for selected park
$.each(rides[''+$(this).val()+''], function(index, value){
// dynamically create the proper DD options
$('select#rides').append('<option>'+value+'</option>');
});
});
</script>
you have to write another file that uses the id of the first selected from the bikes list value to load the options of the second select tag the rides list
then make an empty div on the first file that will be loaded with the result of the second file which is the list of rides
$(function() {
$('#ID_of_the_park_selecttag').change(function() {
var value = $("#ID_of_the_park_selecttag").find('option:selected').text();
$("#ID_OF_THE_DIV").html("");
$("#ID_OF_THE_DIV").load('theOtherFile.php', {"bikename":value } );// value is the value of the select option from the first <select tag>
});});
then on the second file you can get the value of the bike selected as $_POST['bikename'] and do your query then fill the list
I had to do this recently myself. Here's what I did, feel free to use what makes sense to you. I tried what seemed like a simple way to myself.
<select name="department_list" id="department_list" onchange="$('#singleUser').load('yourextraphppage.php?nid='+this.value);">
<option value='none'>Select a department</option>
Then load your first select list with data and close the select tag... Add a blank div where you want the 2nd select. I used the value from the first select list for my parameter for the 2nd select list's query. (it was the foreign key in the 2nd table for the 2nd select list)
<div id="singleUser" class="singleUser">
</div>
Last, you need the additional PHP page that you called from the first select list. Here's a barebones version of my code.
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
I hope this helps. I'm rather busy so I can't go in detail explaining it at the moment. I'll check back later to see if you have any questions.
I was helping somebody a similar page a day or say ago:
2 dropdown selects and the list of options in the second dropdown changed according to the choice selected in the first.
The solution involved the use of <optgroup> elements within the <select> and jQuery (which is not all that easy for a beginner but at least you can copy the code.
See here for the question: jQuery - on page load select optgoup and children in second select by a default selected option in a parent select
And here to see the code in action here: http://jsfiddle.net/goodegg/phj8q/
(although there is a mistake in it).
EDIT
Go here for my forked version of the code: http://jsfiddle.net/annabels/7xksa/
I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.
I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?
my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.
when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,
Ex: let's think about mobile phones, if i select the brand
Nokia
from the left combo box right combo box's content should be changed to
C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73
like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!
regards,
Rangana
The trick is do subscribe to the change event and reset the contents of the second box accordingly.
HTML:
<select id="brand">
<option value="">- select -</option>
<option value="nokia">Nokia</option>
<option value="apple">Apple</option>
</select>
<select id="type"></select>
JavaScript (on ready):
var selectBrand = $("#brand");
var selectType = $("#type");
var optionsList = {
nokia: [
"C6-01",
"E7-00"
],
apple: [
"iPhone 3",
"iPhone 3G",
"iPhone 4"
]
};
selectBrand.change(function() {
var brand = selectBrand.val();
var options = optionsList[brand];
var html;
if (options) {
html = '<option value="">- select -</option>';
$.each(options, function(index, value) {
html += '<option value="' + value + '">' + value + '</option>';
});
} else {
html = '<option value="">Select a brand</option>';
}
selectType.html(html);
}).change();
Full example at See http://www.jsfiddle.net/TJJ8f/
This works by having two things. Firstly, a server that will return JSON for the category you need and, secondly, the code for the front end.
<?php
// Do what you need to
$modelsArray = getModelsForBrand($_REQUEST['brand']);
echo json_encode($modelsArray);
?>
This uses the json_encode function to get the JSON on the array returned by whatever you use to get the models. I haven't used this function myself but it looks pretty simple.
Then your jQuery would look like this:
$("#brandCombo").change(function(){
var chosenBrand = $(this).val(); // Get the value
$.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){
// Successful return from your PHP file
$("#modelCombo").empty();
// For each item returned, add it to your models combo box
$.each(request, function(i,item){
$("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
});
});
});
In this example, brandCombo is the ID of the list with the brands and modelCombo is the ID of the list the models should appear. When the value of brandCombo is changed, it makes the request to your PHP file to get the array of models in JSON. Then it goes through each one and adds a new option to your modelCombo list.
A similar question I answered is here, where I mentioned how to do it with all the data already on the page and in listboxes (hiding/showing them) or by AJAX requests (as the example above).
The other option, as shown in dyve's answer is to have all the information you need on the page already, in the form of a JavaScript object. If you wanted to do this, then then PHP json_encode function could still be of use (although you just call it once with all your data and plop it onto the page).
A number of previous SO posts cover this topic, have a look at this for example: Using javascript and jquery, to populate related select boxes with array structure
My MySQL Database Provides A List of Items (and integer IDs with them) in a <select> and a qty field for usage on my web form (with style display: none so it is hidden). But: I want the user to be able to select how many choices of this type he wants to enter in the form - how can I dynamically make multiple selects?
Example: The products in the inventory are oranges, bananas and peaches. There is one select tag:
<select name="p[0]">
<option value="2">Orange</option>
<option value="23">Banana</option>
<option value="31">Peach</option>
</select>
QTY <input type="text" name="qty[0]" />
Now I want to add another dropdown allowing the user to chose between ordering one, two or three classes of products. he could choose 2, and then two copies of the above code are inserted into the DOM so he can enter two product choices and quantities. (the Script would give them the names p[0] and p[1] etc.)
Can anyone help me here?
The simplest thing is to clone the nodes you already have as many times as needed (as opposed to creating new DOM via document.createElement() or innerHTML.
To start, surround your existing <select> and <input> with a div which has a well-known ID. Also, you want to add another DIV to put the repeated inputs into:
<div id="template">
<select name="p[0]"> ... </select>
QTY: <input name="qty[0]"/>
</div>
<div id="copies">
</div>
Now, create a function that will replicate the template some N number of times:
function makeCopies(num) {
var template = document.getElementById('template');
var output = document.getElementById('copies');
// Delete existing nodes.
output.innerHTML = '';
// We start with 1, not 0, because we already have the template.
for (var i = 1; i < num; i++) {
var copy = template.cloneNode(true);
// Change the input names according to index.
copy.getElementsByTagName('select')[0].name = 'p[' + i + ']';
copy.getElementsByTagName('input')[0].name = 'qty[' + i + ']';
output.appendChild(copy);
}
}