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
Related
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);
}
?>
I have a list of widths in a dropdown box. They are dynamic because each product has different widths so I've setup the code to look for the minimum and maximum. Then it sets up a dropdown list in increments of 1".
Next to the width are 1/8" increments. So for example you could pick 52 1/8.
If the maximum width is 92 inches let's say, the 1/8 increment dropdown box should disappear or disable because since 92 is max.. you can't pick 92 1/8.
How do I make that 1/8ths box disappear or disable? Here is part of my current code for the dropdown box.
<select name="width_str" id="width_str" onchange="doCalc();" style="width:50px;">
<option value="">--</option>
<?php
$counter = $minwidthRS - 1;
$start = $minwidthRS;
for($start; $start < $maxwidthRS + 1; $start++) {
$counter = $counter + 1;
echo "<option value=".$counter.">".$counter."</option>";
}
?>
</select>
Code for the select dropdown box with 1/8ths that I would like to disable or disappear when MAXIMUM above is selected.
<select name="widthfrac_str" id="widthfrac_str" onchange="doCalc();" style="width:50px;">
<option value="">--</option>
<option value="1/8">1/8</option>
<option value="1/4">1/4</option>
<option value="3/8">3/8</option>
<option value="1/2">1/2</option>
<option value="5/8">5/8</option>
<option value="3/4">3/4</option>
<option value="7/8">7/8</option>
</select>
I'm aware of how to send a selected width value over to a PHP page using AJAX and compare it there, but what do I send back in the success callback? Could I send something that tells the container of that 1/8 measurement dropdown to disable or disappear?
Many thanks! If you need more code let me know. The doCalc() script basically uses AJAX and sends the width to php processing page in order to update price instantly.
EDIT (added more code):
Here is part of my script..
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
... lots of variables set here
$.post('db_query.php',
{roomX:roomX, etc. etc. etc.},
function(data) {
data = $.parseJSON(data);
$('#roomname-placeholder').html(data.roomname);
// ... lots of placeholders and code here
});
return false;
};
</script>
Not sure if it helps but I learned a little about using a callback to alter an input field and replacing its value with this: $('input[name=x_login]').val(data.loginid);
It would be great if there was code like that to simply change the other dropdown box disabled=disabled? Does that make sense? I'm still learning programming lingo!
You can call another function with onchange(), which should check the number chosen for the first value. If it is the maximum, then toggle function to hide the second element. A neater solution would be to include the 'check for maximum value and toggle if true' inside doCalc.
Remember to make PHP check also the value, since if user chooses the second value AND then the maximum for the first block, it should hide the second one, but it's value might still be sent.
EDIT:
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
if (roomX == <?php echo $maxwidthRS; ?>)
{
document.getElementById('widthfrac_str').style.display = 'none';
// You also need to make the second element's value 0 within those brackets
}
... lots of variables set here
$.post('db_query.php',
{roomX:roomX, etc. etc. etc.},
function(data) {
data = $.parseJSON(data);
$('#roomname-placeholder').html(data.roomname);
// ... lots of placeholders and code here
});
return false;
};
</script>
There's no problem putting php within javascript if it's in a .php file. It worked as the OP stated in the comments, great!
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 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.
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/