Javascript 第一个下拉菜单自动更改第二个下拉菜单的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11237900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:04:44  来源:igfitidea点击:

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

phpjavascriptjqueryhtml

提问by EnexoOnoma

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 Firstoption 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 secondoption 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!

谢谢!

回答by Praveen Kumar Purushothaman

See below to see the Working Example without using a Database.

请参阅下文以查看不使用数据库工作示例

Working Example Using MySQL Database

使用 MySQL 数据库的工作示例

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

初始 HTML 和 PHP 代码

Now, lets use PHP to first populate the initial <select>:

现在,让我们使用 PHP 首先填充初始值<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 函数,我们可以触发一个 AJAX 事件来<select>使用 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:

现在对于 jQuery 函数,您可以这样做:

<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 selectwith an idas sub.

在 HTML 中,在 之后<select>,您需要给另一个select带有idas sub

<select onchange="ajaxfunction(this.value)">
    <!-- Options would have been initially populated here -->
</select>
<select id="sub"></select>

Processing PHP Source Code

处理 PHP 源代码

Finally the source code of process.php:

最后是源代码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 中替换它。

<?php
    $parent = array("Name", "Place", "Animals");
    foreach ($parent as $id => $name)
        echo '<option value="s', $id,'">', $name,'</option>'
?>

And for the process.php:

而对于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>'
?>

回答by Jared Farrish

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.

关于数据库的部分不是很清楚,因为选择可能会以某种方式“列出”。如果您有其他格式的它们,这是有道理的,或者如果您询问是否需要回拨到数据库 ( postback),答案是否定的。但不清楚你的意思。

Anyhow, you could use a rel=""value (or data-items="") to set the relationship between the one select to the other.

无论如何,您可以使用一个rel=""值(或data-items="")来设置一个选择与另一个之间的关系。

For example:

例如:

CSS

CSS

.cascade {
    display: none;
}

HTML - Modified

HTML - 修改

<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

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/

http://jsfiddle.net/userdude/bY5LF/

回答by Musa

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

这是另一个例子,基本上所有的数据都在一个对象的页面上,你用它来显示不同的 类别 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);
});

回答by Ahsan Rathod

Working solution without using any Database:

不使用任何数据库的工作解决方案:

HTML

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:

CSS:

#PK, #SA { display: none; }

SEE DEMOhttp://jsfiddle.net/rathoreahsan/WyLsh/

查看演示http://jsfiddle.net/rathoreahsan/WyLsh/

States Page:http://fiddle.jshell.net/rathoreahsan/WcKQ2/4/show/

状态页面:http : //fiddle.jshell.net/rathoreahsan/WcKQ2/4/show/

回答by Tats_innit

2 Working Demo for your code:)http://jsfiddle.net/PnSCL/2/ORhttp://jsfiddle.net/PnSCL/

2 代码的工作演示:)http://jsfiddle.net/PnSCL/2/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/

请看这里:http: //api.jquery.com/data/

I have added labelfor relationship here http://jsfiddle.net/PnSCL/2/[ http://www.w3schools.com/tags/tag_option.asp]

label在这里添加了关系http://jsfiddle.net/PnSCL/2/[ http://www.w3schools.com/tags/tag_option.asp]

BehaviourWhen you will select firstoption from select1 then it will show smartphone, chargersotherwise when user will select secondfrom select1 it will show baskeball, voleyballin select2.

行为当您first从 select1 中选择选项时,它将显示smartphone, chargers否则当用户second从 select1 中选择时,它将显示baskeball, voleyball在 select2 中。

Hope this helps, Please let me know if I missed anything.

希望这会有所帮助,如果我错过了什么,请告诉我。

Demo 1

演示 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

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*

演示 2*代码*

$("#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

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>

回答by Saddam Azad

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.

外部 URL 将向我们发送选项列表,然后我们将使用 jquery $(selector).html() 方法将该下拉列表分配给第二个下拉菜单。

<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

完整演示

回答by swapnesh

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.phpphp page --

你的showstate.phpphp 页面——

//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_statediv. You can also use Jquery For this..i think this will help you :) an d let me know if you have any query.

这将加载您#div_statediv 中的内容。您也可以为此使用 Jquery..我认为这会对您有所帮助:) 如果您有任何疑问,请告诉我。

回答by manoj Bhambere

$(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);
            }
        });