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.
Related
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.
I have the following code that programatically generates a dropdown box in php for me.
echo "<select name=\"choice\">";
echo "<option selected=\"selected\" disabled=\"disabled\">Number of Columns</option>";
for ($i = 1; $i <= 10; $i++) {
echo "<option>$i</option>";
}
echo "</select>";
I need to use whatever item the user selects later but I'm not actually sure where the selected value is stored? I know this sounds silly but how do I access the selected item through HTML once the user has made a choice?
Thanks
You don't use HTML to gather the value. HTML is an output language. You use either Javascript or PHP to access those items.
A jQuery Example would look like this:
<form action="submitToPhp.php">
<select id="dropdown" name="dropdown">
<option value='1'>first</option>
<option value='2'>second</option>
</select>
</form>
<script>
$('#dropdown').change(function() {
var selectedItem = $(this).val();
alert(selectedItem);
// Outputs the value of the selected dropdown
});
</script>
A PHP version would be submitting that form to a PHP script:
<?php
$post = $_POST;
$selectedItem = $post['dropdown'];
echo $selectedItem;
// Outputs the value of the selected dropdown item
You could always locate the select element through the parent form element.
eg:
alert(document.forms[0].choice.value);
I want to create a PHP array of a select list. The list have dynamic options, the options are filled with the help of javascript. I want to get all the options on next page.
So I want to create an array of options. Is there any another way to complete this stuff?
Can anybody help me out? Thank you so much in advance.
<script type = "text/javascript">
var val = "";
function removeOptions(selectbox) {
val = selectbox.value;
for (var i = selectbox.options.length-1; i>=1; i--) {
if (selectbox.options[i].selected) {
addOption(document.form1.list2,val,val);
selectbox.remove(i);
document.form1.list1.focus();
}
}
}
function addOption(selectbox,optiontext,optionvalue ){
var optn = document.createElement("OPTION");
optn.text = optiontext;
optn.value = optionvalue;
selectbox.options.add(optn);
}</script>
//list1
<select name="list1" size="7" multiple="multiple" id="jumpMenu" onchange="removeOptions(this)" style="width:200px">
<option>Choose Area...</option>
<?php foreach($dbh->query($sql) as $row){
$a=$row['name'];?>
<option value="<?php echo $a?>"><?php echo $a?></option>
<?php }?>
</select>
//list2
<select name="list2" size="7" multiple="MULTIPLE" id="list2" style="width:170px">
</select>
First: if You want to use multiple with select box, then this selectbox's name have to contain sharp brackets: name="list1[]" and name="list2[]" - this way a PHP will know that this is an array of values.
Second: learn jQuery - though it may seem hard in the beginning it will save You a lot of time and browser-compatibility problems in the future. And jQuery will save Your a*s many times in the future.
For Your purpose I would recommend not just using onchange events but implement additional 4 buttons between the two multiselectboxes that will move the selected options from one to another or all from one to another. This kind of multiselect looks like the one pictured below.
By the first button >> all the options from 1. select are moved to the second one and vice versa with the 4th button <<.
By the second button > only the selected option(s) is(are) moved the second select and vice versa with the third button <.
By this You only catch the click event on the buttons... That is really easy using jQuery...
I need to create 3 dependent drop downs related to each other. So if the first one is selected, related data will be shown in the 2nd drop down, and when an option is selected in the second drop down, in the 3rd drop down some related data will be shown.
And i need to use $_GET on this form, so if a specific option in the second one is slected a massage shows up, and when an option is the 3rd drop down is seleted, the page redirects for example to www.google.com. And i need two none related data in the first filed, so when they are selected, the page redirects for exaple to www.msn.com.
I know it needs JavaScript, but unfortunately I do not know JS for now.
And please do not use " this.value" for sending parameters to JavaScript, because it conflicts with one of my other codes.
( And I don't want the page to reload )
something like this :
Drop down 1 ----------------------- drop down 2 ----------------------- drop down 3
option 1 ( redirect to msn.com)
option 2 ==========================> Option 100 ======================> Option 500
Option 101 Option 501
Option 3 (redirect to google.com) Option 102 (message:Hello )
Option 103 ======================> Option 700
Option 701
I tried hard to explain it, I hope you get what I was trying to say.
Thanks for your help.
Here is a quick and dirty answer...
<html>
<head>
<script type='text/javascript'>
var drop3Options = {"100":["500","501"],"103":["700","701"]};
function drop1Change(){
var value = document.getElementById("drop1").value;
if(value == "msn")
window.location.href = "http://www.msn.com";
else if(value == "google"){
window.location.href = "http://www.google.com";
}
}
function drop2Change(){
var value = document.getElementById("drop2").value;
var drop3List = document.getElementById("drop3");
if(drop3Options[value]){
drop3List.options.length = 0;
for(var i = 0; i < drop3Options[value].length; i++){
drop3List.options[i] = new Option(drop3Options[value][i],drop3Options[value][i]);
}
}
}
</script>
</head>
<body>
<form method='GET' action='serverScript.php'>
<select id='drop1' onchange='drop1Change()'>
<option value='msn'>MSN</option>
<option value='dr2'>DROP 2</option>
<option value='google'>GOOGLE</option>
</select>
<select id='drop2' onchange='drop2Change()'>
<option value='100'>100</option>
<option value='101'>101</option>
<option value='102'>102</option>
<option value='103'>103</option>
</select>
<select id='drop3'>
<option value='500'>500</option>
<option value='501'>501</option>
</select>
<input type='submit' value='SUBMIT'/>
</form>
</body>
</html>
Obviously I don't know what exactly you are using this script to do, so it is hard for me to make assumptions and give you better code, but this will do what I understood the question to be.. I also don't know what server side scripts you will be sending this to. But just change the ACTION attribute in the form to reflect the location of the server script..
The javascript has one global variable (drop3Options). This is an object with two properties which hold 2 arrays for the select 3 options..
So drop3Options['100'] holds an array ['500','501']
and drop3Options['103'] holds an array ['700','701']
when you change a selection box, it calls the appropriate method, this is done by adding the "onchange" attribute to each select element, and it calls the function which looks at the value and does things accordingly
I assume you will need to do more than this, so comment with more specifics and I will gladly help
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?