PHP - Get unselected values of multi select - php

I'm working with a multi select for users to save what there favourite sites are.
Unfortunaly i can't post an image and the application is not working online. I'll try to explain how the multi select shows up:
LEFT BOX (with values that are not selected)
RIGHT BOX (with values that ARE selected)
Users can add values from the left to right box, this is working fine. But when they save, i can only get the new selected values. The values that have been selected earlier are not passed to the form processor. This way i also can't determine if a value is removed from the right column. I want all values from the left box to be posted also. Then i know which values can be "unselected" in the database.
When a value is selected from the left box, it will disappear from this box and appear in the right box.
This is what the form looks like:
<select multiple name="main_categories_1[]" class="multiselect" id="select1">
<option value="26">SAP</option>
<option value="29">SEO</option>
<option value="22">Servicemanager</option>
<option value="28">SharePoint</option>
<option value="34">Stages</option>
<option value="6">Systeembeheerder</option>
<option value="5">Tester</option>
<option value="31">UIDesigner</option>
<option value="35">Zend Dev</option>
</select>
So, to clarify. I DO get the newly selected values, i don't get the unselected values and values that already where selected. I want the unselected values also.
EDIT
Ok, solved it. Like ejrowley said, i need to select all "selected" values with javascript. Done it like this:
$(document).ready(function() {
$('#saveAccount').submit(function() {
$("#select2").find('option').attr('selected',true);
});
});

Even though you solved it... But, just for the sake of variety, you can try this code:
var selected = [];
var noselected = [];
$(document).on('click', '#button', function (){
$.each($('#select2 option'), function (key, value) {
if (!$(this).prop('selected')) {
noselected[key] = $(this).val();
//alert($(this).val());
} else {
selected[key] = $(this).val();
//alert($(this).val());
}
});
});
With this you get 2 arrays, 1 with the selected values and the other with the non-selected.
Here's an JsFiddle Demo.

Related

save all html select box contents to sql server table

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);
}
?>

send selected values of select box to PHP as string

I'm using Select2 3.4.5 for create select boxes,
I use this code for creatre a Multi-Value Select Boxe and everything is fine.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
...
<script>
$("#e1").select2();
</script>
For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:
<?php
foreach ($_POST['mydata'] as $names) {
print "You are selected $names<br/>";
}
?>
But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.
Edit:
I want to send the data as string, not receive it as an array then
change it as string
Server-side with PHP
Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array
$names=implode(',', $_POST['mydata']);
Where $_POST['mydata'] is an array
[0]=>'D1',
[1]=>'D2',
[2]=>'D3'
implode(',', $_POST['mydata']) would be 'D1,D2,D3'
Client-side with jQuery
Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.
$('#formid').on('submit', function(){
$('#e1').val($('#e1').val().join(','));
});
Your form (not given) would need an id <form id="formid" ...>
If you want a client-side solution, try getting the val() and calling join():
$('#e1').val().join()
http://jsfiddle.net/gwgLV/
You can do it with javascript.
<select id="e1" name="mydata" multiple>
<option value="D1">Data1</option>
<option value="D2">Data2</option>
<option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>
javascript code
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function now(){
var el = document.getElementsByTagName('select')[0];
var x = getSelectValues(el);
alert(x);
}
Demo here
Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.

Get values from multiple select boxes with same name? Including its value with jquery and php

I have looked for answers on here and have not found anything that directly can help me so I am going to ask here. I have a form with multiple select boxes:
<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>
<select name="acabados[]">
<option value="1">ABC</option>
<option value="2">DEF</option>
<option value="3">GHI</option>
</select>
As you can see they are the exact same select box. I have told the client to use select multiple but he wants it this way. The user can add as many as these select boxes as they desire (so it could be up to 20 select boxes at a time) and I need to get the value (1 or 2 or 3) and the text inside the option. It is then an array that I need to break down cause I need to add the total values of the select boxes in php. I could either use jquery for collecting the values or php, which ever is easier. Thank you in advance for any help!!
Try this, it will work for dynamically created select elements too.
$(document).on('change', 'select[name="acabados[]"]', function(){
var total = 0;
$('select[name="acabados[]"]').each(function(){
total += parseInt($(this).val());
});
});
total var will contain the total of all the select elements selected value.
If you want to retrieve the values in PHP, you can just use $_POST['acabados'] and it will contain all the values selected in each menu. See a demo. As long as you include the [] after the name, it will compound all the values for any element with that name into a single array. You can even mix select menus, inputs, and textareas together!
$(function () {
var $select = $('select');
$select.on('change', function () {
var output = 0;
for (var i = 0, len = $select.length; i < len; i++) {
output += parseInt($select.eq(i).val());
}
//the `output` variable now contains the addition of all the values from the `acabados[]` select elements
});
});
Here is a demo: http://jsfiddle.net/aPXXA/1/
You can change var $select = $('select'); to var $select = $('[name="acabados[]"]'); to only select the select elements with the acabados[] name attribute.
Why not just give them different id's and do the count in jquery/javascript. Alternatively give them all the same class, and do .each() to grab the values in all of them.

Changing contents of HTML select based on dropdown

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.

how to populate the second drop down using the selected value in first drop down?

Say I have two drop downs which are populated when the my jsp loads
<select id="Group" name="group"> -- first drop down
<option value="0001">1</option>
<option value="0002">2</option>
</select>
<select id="subGroup" name="class"> -- second drop down
<option value="0001-000">A</option> -- sub group associated with option value 001
<option value="0001-010">B</option>
<option value="0001-020">C</option>
<option value="0001-030">D</option>
<option value="0001-040">E/option>
<option value="0002-000">F</option> -- sub group associated with option value 002
<option value="0002-010">G</option>
<option value="0002-020">H</option>
<option value="0002-040">I</option>
</select>
Now I need to filter the second drop down based on the selected value in first drop down. I can't use the PHP code which uses the DB callback methods. in my script I have something like this.
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').filter(function( {return!$(this).val().indexOf(groupVal)!=-1);}).remove();
});
the script is working fine, it removes all the options other then the one selected. but my problem is that next time when i select other value in first drop down, second drop down goes empty. I even worked with hide/show but guess they wont work with <select> :(
is there any way by which I can repopulate the second drop down when I selected some other option in first drop down?
If you are removing elements, you aren't getting them back. Use hide() and show() as you yourself suggested:
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
$('#subGroup option').hide();
$('#subGroup option[value^='+groupVal+']').show();
});
In other words, every time the #Group selectbox is changed, hide all options in #subGroup and show only the ones whose value attribute starts with groupVal.
Store all the options for the second select box into a array when the page loads. Then populate the select box from that array on change.
You are removing the second "batch" of options so they don't exists any more the next time you want to use them.
In order to do that you need to store all available options somewhere and then repopulate from that data set. for example
var availableOptions = {
'groupOne': {/* options as {value: '', text: ''} */},
'groupTwo': {/* options as {value: '', text: ''} */}
};
$("#Group").change(function() {
var groupVal = $(this).find("option:selected").val();
var sub = $('#Subgroup');
$.each(availableOptions[groupVal], function(i, data){
sub.append('<option value="'+data+'">'+data.text+'</option>');
});
There's also a related select box plugin by Remy sharp that I've had success with if you want to try:
http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/

Categories