Extract options from select list PHP - php

I am looking for a way to extract the options, from a HTML select list, and place them into a comma-delimited list. Some of the lists are rather large, so I am looking for a quick way to do this. Any help is appreciated.
So for example, the list below...
<select>
<option value="325">35</option>
<option value="326">45</option>
<option value="327">55</option>
<option value="328">65</option>
</select>
...would become:
35,45,55,65

you can try something like this on thew client side wit5h jquery
var arr = new Array();
$("#id option").each(function()
{
arr.push($(this).text())
});
arr.toString();
var x=document.getElementById("demo");
x.innerHTML=arr;
<p id="demo"></p>
http://jsfiddle.net/b4JBx/ working example

Plain Javascript (since you mentioned client-side is OK):
var elements = document.getElementsByTagName('option'),
list = [];
for (var i=0; i<elements.length; i++) {
list.push(elements[i].innerText);
}
var result = list.join(',');

Related

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.

embedding multiple values in options of <select>

I need to embedd 2 values in each of the options of a drop down list and then need to be able to pass both of them to a JavaScript function.
<select onChange="display(<?=$manufacturers_id?>,<?=$modelID?>,this.value1,this.value2);">
..
..
echo "<option value1=\"".$variantID."\" value2=\"".$month_year."\">".$products_variant." ".$month_year."</option>";
..
..
</select>
As you can see this HTML code is generated by PHP, I need these two values fetched from database to passed to a JS function.
I am open to suggestions on better way of doing this?
you cannot add many values in an option.
instead you can use datasets (html5), like:
<select id="myselect">
<option data-this="foo" data-that="bar">
</select>
the javascript to read these values is:
var d = document.getElementById("myselect");
var _this = d.options[d.selectedIndex].dataset["this"];
var _that = d.options[d.selectedIndex].dataset["that"];
if you dont want to mess with datasets, you can store a JSON object:
...
<option value='<?php echo json_encode(array("foo"=>1,"bar"=>2)); ?>'>
...
and extract the data like:
var d = document.getElementById("myselect");
var option_value = JSON.parse( d.options[d.selectedIndex].value );
you choose
EDITED:
change this:
<select onChange="display(<?=$manufacturers_id?>,<?=$modelID?>,this);">
function display(manufacturers_id,modelid,obj) {
... json way
var option_value = JSON.parse(obj.options[obj.selectedIndex].value);
// option_value.foo = 1;
... dataset way
var _this = obj.options[obj.selectedIndex].dataset["this"];
// _this will have the "foo" value
}
I would render the options like this:
<option data-value1="X" data-value2="Y">
Then deal with these data- attributes however you want (with jQuery's data("value1") method, with the native getAttribute("data-value1"), etc.

Get the values of form array with jQuery

Have looked quite hard for this answer but having no luck.
I have 3 select lists in a form. The first list is already part of the form, the second two are dynamically added. These select lists are part of an array named event_staff[].
<select name="event_staff[]" class="event_staff">
<option value="1">Mark</option>
<option value="2">Sue</option>
</select>
<select name="event_staff[]" class="event_staff">
<option value="1">Mark</option>
<option value="2">Sue</option>
</select>
<select name="event_staff[]" class="event_staff">
<option value="1">Mark</option>
<option value="2">Sue</option>
</select>
The user can select a person from each of the lists which are then to be sent via AJAX/Json to a a PHP script which iterates through the array and inserts the selected staff into the database.
For the life of me I dont know how to access the selected values of the lists and send them as an array to the PHP script.
Because the select lists are dynamically created I am not using IDs to access them. I was instead relying on accessing their values by name.
select[name='event_staff[]']
I had tried this code but the alert is returning empty:
var event_staff = new Array();
$("select[name='event_staff[]']:selected").each(function() {
event_staff.push($this).attr('value');
});
alert(event_staff);
Thanks.
Solved with the following, but not sure if its pretty or not:
var event_staff = new Array();
$('select[name="event_staff[]"] option:selected').each(function() {
event_staff.push($(this).attr('value'));
});
Just seems I needed the option:selected. While this doesnt seem to create an array, I have exploded the variable in the PHP on the delimiter and created the array that way.
var event_staff = [];
$("select[name='event_staff[]'] option:selected").each(function () {
event_staff.push( this.value );
});
alert(event_staff);
Here's the fiddle: http://jsfiddle.net/Rx6Fk/
If you instead want the name of that person, use .text():
var event_staff = [];
$("select[name='event_staff[]'] option:selected").each(function() {
event_staff.push( $.text(this) );
});
alert(event_staff);
Here's the fiddle: http://jsfiddle.net/Rx6Fk/1/
Alternatively, you could use jQuery's .map method:
var event_staff = $("select[name='event_staff[]'] option:selected").map(function() {
return $.text(this);
}).get();
alert(event_staff);
Here's the fiddle: http://jsfiddle.net/Rx6Fk/2/
.val() will return the selected value for select.
var event_staff = [];
$('select[name="event_staff[]"]').each(function() {
event_staff.push($(this).val());
});
alert(event_staff);
The demo: http://jsfiddle.net/fHbaw/

Get selected select value from a listbox with mysql data to open another listbox and fetch mysql data using this value

Im starting in javascript so, I need to do this : From a list box(already has mysql data using php) I want to get the current selection id (select,selected I think in Java) and fill a listbox with data using the id of the first listbox.But this must happens on onChange property of the listbox1 but on selection.
Here is what I have so far
Html code
Select a Region
$result_disp = mysql_query($query_disp, $cn);
$res=mysql_select_db("xxxx",$cn) or die("Note: " . mysql_error());
$res=mysql_query("select Region_ID, Region_Description from regions");
while($query_data = mysql_fetch_array($res))
{
?>
<option value="<? echo $query_data["Region_ID"]; ?>"
<?php if ($query_data["Region_ID"]==$_post['Region_ID']) ?>>
<? echo $query_data["Region_Description"]; ?></option>
<? } ?>
<select name="Dep" id="Items">
<option>Département</option>
</select>
javascript
function setSelect(id,value) {
var sel = document.getElementById(id);
var option, options = sel.options;
var i = options.length;
while (i--) {
option = options[i];
option.selected = (option.value == value)? true : false;
}
}
thanks in advance!
If you want to manipulate and query the DOM, use the great javascript library jQuery.
Once you have jQuery downloaded and included in your page, you can then do things like this:
<select id='myFirstSelect'>
<option value="1"/>
<option value="2"/>
</select>
javascript: (Bind a function to the 'changed'-event)
$('#myFirstSelect').changed(function(){
var selectedValue = $(this).val();
//do something with selectedValue, e.g. $('#someOtherSelect').val(selectedValue);
});
I haven't tested this code, it's just to give you an idea how much faster and more elegant you get ahead, once you get into jQuery (keywords: Selectors and Events)

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.

Categories