First drop down menu to auto change the options of a second dropdown

I have two drop down menus where the options are not get from the database.

The first one, lets the user to select a category.

<select name="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>

The options of the second, are depended from the choice in the first dropdown menu. For example, if the user chooses the First option then the second dropdown will show

<select name="items">
    <option value="3">Smartphone</option>
    <option value="8">Charger</option>
</select>

but when the user change his mind, or select the second option first, then the second dropdown will now show

<select name="items">
    <option value="1">Basketball</option>
    <option value="4">Volleyball</option>
</select>

My question is how can I achieve this ? Can this be done without using a database?

Thank you!

Answers:

Answer

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>'
?>
Answer

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/

Answer

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>
Answer

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/

Answer

Just suggesting how you can do it --

<select name="country" id="country" onChange="showState();" >
<option value="">Select Country</option>
<option value="1">India</option>
<option value="2">Nepal</option>
</select>

Your Script--

<script type="text/javascript">
function showState( )
{
var value = document.getElementById('country').value;
var url = '<?php echo base_url ?>showstate.php';
$.ajax({
type: "GET",
url: url,
data:{'country':value},
success:function(results)
{   
    $('#div_state').html(results);
}
});
}
</script>

Your showstate.php php page --

//INCLUDE CONNECTION file to for db query
$type = $_GET['country'];

//Your DB QUERIES
//Your data on Get condition
/*USING SWITCH--
switch ($type) {
case "India":
    echo "I m in India";
    break;
case "Nepal":
    echo "I am in Nepal";
    break;

This will load the content in your #div_state div. You can also use Jquery For this..i think this will help you :) an d let me know if you have any query.

Answer

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);
});
Answer

Here is a very simple full example :

The external URL will send us the list of option and then we will assign that drop down list to the second drop down menu using jquery $(selector).html() method.

<script type="text/javascript">

    $("#country").on('change',function(){
        var country= $(this).val();

        $.ajax({
            url: 'cities.php' ,
            type: 'POST',
            data: "country="+country,
            success: function(cities)
            {
                $("#cities").html(cities);
            }

        });
    });
</script>  

Full Demo

Answer
$(document).ready(function(){
    $('#causes').change(function(){

         $.getJSON("<?=URL.$param->module."/".$param->controller?>/getcourtcauses",{causeId:  $(this).val()}, function(j){ 

        var options = '';
        if(j.length > 1 )
        {
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
            }
            if($('#subcauses').hide())
                {
                    $('#subcauses').show();
                }
                $('#subcauses').attr('disabled', false);
            $("#subcauses").html("");
            $("#subcauses").html(options);
         }
        else
            {
                $('#subcauses')
                    .find('option')
                    .remove()
                    .end();
                 $('#subcauses').attr('disabled', true);
            }
        });  

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.