First drop down menu to auto change the options of a second dropdown
See below to see the Working Example without using a Database.
Working Example Using MySQL Database
If you wanna connect it using Database, yeah, it is surely possible. Consider this table:
CREATE TABLE `contents` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR (255),
`parent` INT DEFAULT 0
);
INSERT INTO `contents` (`name`, `parent`) VALUES
('Names', 0),
('Places', 0),
('Animals', 0),
('Praveen', 1),
('Bill Gates', 1),
('Steve Jobs', 1),
('India', 2),
('New York', 2),
('London', 2),
('Singapore', 2),
('Cat', 3),
('Dog', 3),
('Tiger', 3),
('Deer', 3)
Table Structure
+----+------------+--------+
| id | name | parent |
+----+------------+--------+
| 1 | Names | 0 |
| 2 | Places | 0 |
| 3 | Animals | 0 |
| 4 | Praveen | 1 |
| 5 | Bill Gates | 1 |
| 6 | Steve Jobs | 1 |
| 7 | India | 2 |
| 8 | New York | 2 |
| 9 | London | 2 |
| 10 | Singapore | 2 |
| 11 | Cat | 3 |
| 12 | Dog | 3 |
| 13 | Tiger | 3 |
| 14 | Deer | 3 |
+----+------------+--------+
Initial HTML & PHP Code
Now, lets use PHP to first populate the initial <select>
:
<?php
mysql_connect();
mysql_select_db("contents");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = 0");
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>
Now the <select>
is ready. With its onchange function, we can fire an AJAX event to get the new <select>
with the data provided by the parent <select>
.
<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>
Now for the jQuery function, you can do this way:
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?parent=' + parent;
success: function(data) {
$("#sub").html(data);
}
});
}
</script>
In the HTML, after the <select>
, you need to give another select
with an id
as sub
.
<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>
<select id="sub"></select>
Processing PHP Source Code
Finally the source code of process.php
:
<?php
mysql_connect();
mysql_select_db("contents");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = " . mysql_real_escape_string($_GET["parent"]));
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>
Working Example without using a Database
You just need to replace this in the PHP.
<?php
$parent = array("Name", "Place", "Animals");
foreach ($parent as $id => $name)
echo '<option value="s', $id,'">', $name,'</option>'
?>
And for the process.php
:
<?php
$parent = array("Name", "Place", "Animals");
$s0 = array("Praveen", "Bill Gates", "Steve Jobs");
foreach (${$_GET["parent"]} as $id => $name)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>
The part about the database isn't really clear, since the selects would presumably be "listed" in some fashion. If you have them in some other format, that makes sense, or if you're asking if a call back to the database (postback
) is necessary, the answer is no. But it's not clear what you mean.
Anyhow, you could use a rel=""
value (or data-items=""
) to set the relationship between the one select to the other.
For example:
CSS
.cascade {
display: none;
}
HTML - Modified
<select name="category">
<option value="0">None</option>
<option value="1" rel="accessories">Cellphones</option>
<option value="2" rel="sports">Sports</option>
<option value="3" rel="cars">Cars</option>
</select>
<select name="items" class="cascade">
<option value="3" class="accessories">Smartphone</option>
<option value="8" class="accessories">Charger</option>
<option value="1" class="sports">Basketball</option>
<option value="4" class="sports">Volleyball</option>
<option value="6" class="cars">Corvette</option>
<option value="2" class="cars">Monte Carloe</option>
</select>
jQuery
$(document).ready(function(){
var $cat = $('select[name=category]'),
$items = $('select[name=items]');
$cat.change(function(){
var $this = $(this).find(':selected'),
rel = $this.attr('rel'),
$set = $items.find('option.' + rel);
if ($set.size() < 0) {
$items.hide();
return;
}
$items.show().find('option').hide();
$set.show().first().prop('selected', true);
});
});
http://jsfiddle.net/userdude/bY5LF/
Here is another example, basically all the data is on the page in an object and you use it to display the different catagories FIDDLE
var categories = {
"None":[{value:'3', text:'No cataegory selected'}],
"First":[{value:'1', text:'Bmw'},{value:'2', text:'Benz'}],
"Second":[{value:'4', text:'Playstation'},{value:'5', text:'Xbox'},{value:'10', text:'Wii'}],
"Third":[{value:'6', text:'Dell'},{value:'7', text:'Acer'}],
"Fourth":[{value:'8', text:'Audi'},{value:'9', text:'Datsun'}]
};
function selectchange(){
var select = $('[name=items]');
select.empty();
$.each(categories[$(':selected', this).text()], function(){
select.append('<option value="'+this.value+'">'+this.text+'</option>');
});
}
$(function(){
$('[name=category]').on('change', selectchange);
});
2 Working Demo for your code :)
http://jsfiddle.net/PnSCL/2/ OR http://jsfiddle.net/PnSCL/
It is achievable but you need to make a relationship between first and second select.
Please take a look in here as well: http://api.jquery.com/data/
I have added label
for relationship here http://jsfiddle.net/PnSCL/2/ [ http://www.w3schools.com/tags/tag_option.asp ]
Behaviour When you will select first
option from select1 then it will show smartphone, chargers
otherwise when user will select second
from select1 it will show baskeball, voleyball
in select2.
Hope this helps, Please let me know if I missed anything.
Demo 1
Code
$("#category").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[label=' + id + ']');
$('#select2').html(options);
// alert(options);
});
HTML
<select name="select1" id="category">
<option value="0">None</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<select name="items" id="select2">
<option value="3" label="1">Smartphone</option>
<option value="8" label="1">Charger</option>
<option value="1" label="2">Basketball</option>
<option value="4" label="2">Volleyball</option>
</select>
DEMO 2 *code*
$("#category").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
alert(options);
});
HTML
<select name="select1" id="category">
<option value="0">None</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<select name="items" id="select2">
<option value="1">Smartphone</option>
<option value="1">Charger</option>
<option value="2">Basketball</option>
<option value="2">Volleyball</option>
</select>
Working solution without using any Database:
HTML
<select name="country" id="country" onChange="showState();">
<option value="">Select Country</option>
<option value="1">Pakistan</option>
<option value="2">Saudi Arabia</option>
</select>
<div id="div_state"></div>
Jquery
<script>
function showState()
{
$('body').css('cursor','wait');
var value = document.getElementById('country').value;
var url = 'http://fiddle.jshell.net/rathoreahsan/WcKQ2/4/show/';
$.ajax({
type: "GET",
url: url,
data:{'country':value},
success:function(results)
{
$('#div_state').html(results);
if (value == "1")
{
$('#PK').css('display','block')
}
else if (value == "2")
{
$('#SA').css('display','block')
}
$('body').css('cursor','default');
}
});
}
</script>
CSS:
#PK, #SA { display: none; }
SEE DEMO http://jsfiddle.net/rathoreahsan/WyLsh/
States Page: http://fiddle.jshell.net/rathoreahsan/WcKQ2/4/show/