embedding multiple values in options of <select> - php

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.

Related

Extract options from select list 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(',');

Using jQuery or Javascript to find dropdown option value

I am dynamically generating a dropdown list on the page when a user loads it. I'd like to get the value of the dropdown using jquery or javascript.
The tricky part is that the dropdown will have a value as such:
"I love Rabbits ($19.95)"
I want to get the value of the dropdown and then isolate the value inside of the brackets.
Any ideas?
Cheers!
Getting the value is easy, use val(). That will be a string.
Then you just grab the value with a regex, probably with a capture group; for instance:
var value, m, innerValue;
value = $("selector for select box").val();
m = /\(([^)]+)/.exec(value);
if (m) {
innerValue = m[1];
}
That regex says: "Find a ( and then capture everything following it that isn't a )". Then we take the value of the capture group.
Could you not have your select in the following format:
<select name="opinions_price">
<option value="19.45">I love rabbits (£19.45)</option>
<option value="12.45">I hate parakeets (£12.45)</option>
<option value="3.24">I am indifferent to possums (£3.24)</option>
</select>
Then simply do:
var price = $('select option:selected').val();
If you want to use the data attributes instead (assume the select is in a loop, you know how to do that):
<select name="opinions_price">
<?php foreach($things as $thing) { ?>
<option data-price="<?php echo $thing['price']; ?>" data-id="<?php echo $thing['id']; ?>">[..]</option>
<?php } ?>
</select>
Then simply do:
var price = $('select option:selected').data('price');
var id = $('select option:selected').data('id');
Saves a (possibly) expensive Regex?

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)

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.

Categories