简体   繁体   English

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

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

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>

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).on('ready', function () {

    $("#source").on('change', function () {
        var el = $(this);
        if (el.val() === "ONLINE") {
            $("#status").append("<option>SHIPPED</option>");
        } else if (el.val() === "MANUAL") {
            $("#status option:last-child").remove();
        }
    });

});

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更多细节,我的意思是动态和更多的依赖请看我的文章 创建动态下拉列表

In this jsfiddle you'll find a solution I deviced.这个 jsfiddle 中,您会找到我设计的解决方案。 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.这个想法是在 html 中有一个选择器对,并根据第一个选择的选项使用(普通)javascript来过滤依赖选择器中的选项。 For example:例如:

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

[ Edit 2021 ] or use data-attributes, something like: [ Edit 2021 ] 或使用数据属性,例如:

 document.addEventListener("change", checkSelect); function checkSelect(evt) { const origin = evt.target; if (origin.dataset.dependentSelector) { const selectedOptFrom = origin.querySelector("option:checked") .dataset.dependentOpt || "n/a"; const addRemove = optData => (optData || "") === selectedOptFrom ? "add" : "remove"; document.querySelectorAll(`${origin.dataset.dependentSelector} option`) .forEach( opt => opt.classList[addRemove(opt.dataset.fromDependent)]("display") ); } }
 [data-from-dependent] { display: none; } [data-from-dependent].display { display: initial; }
 <select id="source" name="source" data-dependent-selector="#status"> <option>MANUAL</option> <option data-dependent-opt="ONLINE">ONLINE</option> <option data-dependent-opt="UNKNOWN">UNKNOWN</option> </select> <select id="status" name="status"> <option>OPEN</option> <option>DELIVERED</option> <option data-from-dependent="ONLINE">SHIPPED</option> <option data-from-dependent="UNKNOWN">SHOULD SELECT</option> <option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option> </select>

    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>

You're better off making two selects and showing one while hiding the other.你最好做两个selects并显示一个同时隐藏另一个。

It's easier, and adding options to selects with your method will not work in IE8 (if you care).它更容易,并且使用您的方法向selects添加options在 IE8 中不起作用(如果您关心)。

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 } } ?>

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM.为此,我注意到显示和隐藏标签比为 DOM 添加和删除标签要好得多。 It performs better that way.它的性能更好。

The answer should be updated to replace the defunct functions .change & .ready应该更新答案以替换已失效的函数.change & .ready

$(document).on('ready',function()  {

    $("#source").on('change', function(){
        var el = $(this);
        if (el.val() === "ONLINE") {
            $("#status").append("<option>SHIPPED</option>");
        } else if (el.val() === "MANUAL") {
            $("#status option:last-child").remove();
        }
    });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM