jQuery 下拉框取决于在另一个下拉框中选择的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19728666/
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-27 00:30:21  来源:igfitidea点击:

Drop-down box dependent on the option selected in another drop-down box

javascriptjqueryhtmlformsdrop-down-menu

提问by samyb8

I have 2 different SELECT OPTION in a form.

我在一个表单中有 2 个不同的 SELECT OPTION。

The first one is Source, the second one is Status. I would like to have different OPTIONS in my Status drop-down list depending on the OPTION selected in my Source drop-down.

第一个是源,第二个是状态。我希望在我的状态下拉列表中有不同的选项,具体取决于在我的源下拉列表中选择的选项。

Source:

来源:

<select id="source" name="source">
     <option>MANUAL</option>
     <option>ONLINE</option>
</select>

Status:

地位:

<select id="status" name="status">

</select>

Options: - If Source is MANUAL, then Status is OPEN or DELIVERED - If Source is ONLINE, then Status is OPEN or DELIVERED or SHIPPED

选项: - 如果来源为 MANUAL,则状态为 OPEN 或 DELIVERED - 如果来源为 ONLINE,则状态为 OPEN 或 DELIVERED 或 SHIPPED

My non-working attempt:

我的非工作尝试:

            <script>
            $(document).ready(function () {
            var option = document.getElementById("status").options;
            if (document.getElementById('source').value == "MANUAL") {
                $("#status").append('<option>OPEN</option>');
                $("#status").append('<option>DELIVERED</option>');
                }
            if (document.getElementById('source').value == "ONLINE") {
                $("#status").append('<option>OPEN</option>');
                $("#status").append('<option>DELIVERED</option>');
                $("#status").append('<option>SHIPPED</option>');
                }
            });
            </script>

回答by Psych Half

try something like this... jsfiddle demo

尝试这样的事情...... jsfiddle演示

HTML

HTML

 Source:   <select id="source" name="source">
     <option>MANUAL</option>
     <option>ONLINE</option> </select>

Status:

<select id="status" name="status">
    <option>OPEN</option>
      <option>DELIVERED</option>
    </select>

JS

JS

$(document).ready(function() {

  $("#source").change(function() {

    var el = $(this) ;

    if(el.val() === "ONLINE" ) {
    $("#status").append("<option>SHIPPED</option>");
    }
      else if(el.val() === "MANUAL" ) {
        $("#status option:last-child").remove() ; }
  });

});

回答by Jyotiranjan

I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.

我发布这个答案是因为这样你将永远不需要任何像 jQuery 和任何其他插件这样的插件,这有通过简单的 javascript 的解决方案。

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script language="javascript" type="text/javascript">
    function dynamicdropdown(listindex)
    {
        switch (listindex)
        {
        case "manual" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            break;
        case "online" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
            break;
        }
        return true;
    }
    </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
    <div class="category_div" id="category_div">Source:
        <select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
        <option value="">Select source</option>
        <option value="manual">MANUAL</option>
        <option value="online">ONLINE</option>
        </select>
    </div>
    <div class="sub_category_div" id="sub_category_div">Status:
        <script type="text/javascript" language="JavaScript">
        document.write('<select name="status" id="status"><option value="">Select status</option></select>')
        </script>
        <noscript>
        <select id="status" name="status">
            <option value="open">OPEN</option>
            <option value="delivered">DELIVERED</option>
        </select>
        </noscript>
    </div>
    </body>
</html>

For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list

更多细节,我的意思是动态和更多的依赖请看我的文章 创建动态下拉列表

回答by KooiInc

In this jsfiddleyou'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:

这个 jsfiddle 中,您会找到我设计的解决方案。这个想法是在 html 中有一个选择器对,并根据第一个选择的选项使用(普通)javascript来过滤依赖选择器中的选项。例如:

<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

Uses (in the jsFiddle)

用途(在 jsFiddle 中)

 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea',
               'South Korea','India','Malaysia',
               'Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

回答by chetan

    function dropdownlist(listindex)
    {
         document.getElementById("ddlCity").options.length = 0;
         switch (listindex) 
         {
             case "Karnataka":
                     document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                     document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
                     document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
                     document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
                     document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");

                 break;

             case "Tamilnadu":
                 document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                 document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
                 document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");


                 break;
         }

    }

* State: --Select-- Karnataka Tamilnadu Andra pradesh Telngana

* 州:--Select-- Karnataka Tamilnadu Andra pradesh Telngana

    <div>
        <p>

            <label id="lblCt">
            <span class="red">*</span>
                City:</label>
            <select id="ddlCity">
               <!-- <option>--Select--</option>
                <option value="1">Dharawad</option>
                <option value="2">Belgum</option>
                <option value="3">Bagalkot</option>
                <option value="4">Haveri</option>
                <option>Hydrabadh</option>
                <option>Vijat vada</option>-->
            </select>
            <label id="lblCity"></label>
        </p>
    </div>

回答by Matthew Rapati

You're better off making two selectsand showing one while hiding the other.

你最好制作两个selects并展示一个同时隐藏另一个。

It's easier, and adding optionsto selectswith your method will not work in IE8 (if you care).

它更容易,并且添加optionsselects您的方法在 IE8 中不起作用(如果您关心)。

回答by Carl Angelo Nievarez

I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.

我希望以下代码可以帮助或解决您的问题,或者您认为无法理解,请访问http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/

HTML DYNAMIC DEPENDENT SELECT

HTML 动态依赖选择

<div class="frmDronpDown">
<div class="row">
    <label>Country:</label><br/>
    <select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
    <option value="">Select Country</option>
    <?php
    foreach($results as $country) {
    ?>
    <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
    <?php
    }
    ?>
    </select>
</div>
<div class="row">
    <label>State:</label><br/>
    <select name="state" id="state-list" class="demoInputBox">
    <option value="">Select State</option>
    </select>
</div>

GETTING STATES VIA AJAX

通过 AJAX 获取状态

<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
    $("#state-list").html(data);
}
});} </script>

READ STATE DATABASE USING PHP

使用 PHP 读取状态数据库

<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>

回答by asiby

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.

为此,我注意到显示和隐藏标签比为 DOM 添加和删除标签要好得多。它的性能更好。