Javascript 使用 JQuery 和 ajax 帖子在表单中选择另一个下拉列表时更改下拉值

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

Change dropdown value when another dropdown selected in a form using JQuery & ajax post

javascriptphpjqueryhtmlajax

提问by user3224142

how to change a dropdown value based on another dropdown value?

如何根据另一个下拉值更改下拉值?

I will have 3 dropdown value in a form just like below:

我将有 3 个下拉值,形式如下:

<form method="post" action="find.pgp"><div class="form-group col-lg-2">
            <label>Country</label>
            <select id="country" name="country" class="form-control">
                <option value="1">Japan</option>
                <option value="2">China</option>
                <option value="3">New Zealand</option>
            </select>
        </div>
        <div class="form-group col-lg-2">
            <label>province</label>
            <select name="province" class="form-control">
                <option value="1">a province</option>
            </select>
        </div>

<div class="form-group col-lg-2">
            <label>city</label>
            <select name="city" class="form-control">
                <option value="1">a city</option>
            </select>
        </div> <input type="submit> </form>

What I want is,
1st I choose a country name
2nd Province Changed into based on country relation to it's table on db
3rd I choose province then value of city dropdown changed into city which has relation to province table in database
4th I will submit all this to find something in db

我想要的是,
第一个我选择一个国家名称
第二个省根据国家与它在数据库上的表的关系更改为
第 3 个我选择省然后城市下拉列表的值更改为与数据库中的省表有关系的城市
第 4 个我将提交所有这些在 db 中找东西

So what I am supposed to do with JQuery and Ajax to retrieve value and change the dropdown value? Thank you

那么我应该如何使用 JQuery 和 Ajax 来检索值并更改下拉值?谢谢

回答by Chay22

So basically you need to disable selectfirst unless for country right? Or something else that would make the country field selected first.

所以基本上你需要先禁用,select除非是国家对吧?或者其他可以使国家/地区字段首先被选中的东西。

<form id="myForm">
    <div class="form-group col-lg-2">
        <label>Country</label>
        <select id="country" name="country" class="form-control">
            <option value="1">Japan</option>
            <option value="2">China</option>
            <option value="3">New Zealand</option>
        </select>
    </div>
    <div class="form-group col-lg-2">
        <label>province</label>
        <select name="province" class="form-control" disabled>
            <option value="1">a province</option>
        </select>
    </div>

    <div class="form-group col-lg-2">
        <label>city</label>
        <select name="city" class="form-control" disabled>
            <option value="1">a city</option>
        </select>
    </div>
    <input type="submit">
</form>

As I don't know what is your server response is. I'm assuming as this one

因为我不知道您的服务器响应是什么。我假设这个

{"response": " <option selected value=\"countryprovince1\">Selected Province1</option><option selected value=\"countryprovince2\">Selected Province2</option><option selected value=\"countryprovince3\">Selected Province3</option>"}

And by this means, I can simply use jQuery html()

通过这种方式,我可以简单地使用 jQuery html()

    //Select country first
$('select[name="country"]').on('change', function() {
    var countryId = $(this).val();

    $.ajax({
        type: "POST",
        url: "get-province.php",
        data: {country : countryId },
        success: function (data) {
                    //remove disabled from province and change the options
                    $('select[name="province"]').prop("disabled", false);
                    $('select[name="province"]').html(data.response);
        }
    });
});


$('select[name="province"]').on('change', function() {
    var provinceId = $(this).val();

    $.ajax({
        type: "POST",
        url: "get-city.php",
        data: {province : provinceId },
        success: function (data) {
                    //remove disabled from city and change the options
                    $('select[name="city"]').prop("disabled", false);
                    $('select[name="city"]').html(data.response);
        }
    });
});

//once all field are set, submit
$('#myForm').submit(function () { 
    $.ajax({
        type: "POST",
        url: "find.php",
        data: $('#myForm').serialize(),
        success: function (data) {
                //success
        }
      });
    });
});

回答by Brett Gregson

First add an idto your province selectand your city select

首先添加一个id到你的省select和你的城市select

<form method="post" action="find.pgp">
    <div class="form-group col-lg-2">
        <label>Country</label>
        <select id="country" name="country" class="form-control">
            <option value="1">Japan</option>
            <option value="2">China</option>
            <option value="3">New Zealand</option>
        </select>
    </div>

    <div class="form-group col-lg-2">
        <label>province</label>
        <select name="province" class="form-control" id="province">
        </select>
    </div>

    <div class="form-group col-lg-2">
        <label>city</label>
        <select name="city" class="form-control" id="select"></select>
    </div>
    <input type="submit">
</form>

Then, assuming you already have jQuery setup on the page:

然后,假设您已经在页面上设置了 jQuery:

<script>
    $(function(){
        // event called when the country select is changed
        $("#country").change(function(){
            // get the currently selected country ID
            var countryId = $(this).val();
            $.ajax({
                // make the ajax call to our server and pass the country ID as a GET variable
                url: "get_provinces.php?country_id=" + countryId,
            }).done(function(data) {
                // our ajax call is finished, we have the data returned from the server in a var called data
                data = JSON.parse(data);

                // loop through our returned data and add an option to the select for each province returned
                $.each(data, function(i, item) {
                    $('#province').append($('<option>', {value:i, text:item}));
                });

            });
        });
    });
</script>

And your get_provinces.phpscript which you are calling with ajax:

以及您get_provinces.php使用 ajax 调用的脚本:

<?php
    /// we can access the country id with $_GET['country_id'];
    // here you can query your database to get the provinces for this country id and put them in an array called $provinces where the key is the id and the value is the province name

    // this is a dummy array of provinces, you will replace this with the data from your database query
    $provinces = array(6=>"Province One",54=>"Province Two",128=>"Province Three");
    echo json_encode($provinces);
?>

That's the basic idea. You will obviously need to change your get_provinces.phpto query your database and return the correct data using the country id. You'll be able to figure out how to do the cities from this as well

这就是基本的想法。您显然需要更改您get_provinces.php的查询数据库并使用国家/地区 ID 返回正确的数据。你也将能够弄清楚如何从这里做城市

回答by Muhammad Umar

You have to use .change() event handler for this purpose

为此,您必须使用 .change() 事件处理程序

    $(document).ready(function() {
    $('.form-group col-lg-2').change(function() {
    var $select = $(this).val();
    // here you can apply condition on $select to apply different scenarios.


     });
   });

This is just an idea. You can have a look on different examples available online. Please have a look on the following webpage to get an idea of this functionality with database.

这只是一个想法。您可以查看在线提供的不同示例。请查看以下网页以了解此数据库功能。

https://css-tricks.com/dynamic-dropdowns/

https://css-tricks.com/dynamic-dropdowns/

回答by Wajahat Bashir

Use just these two lines, it's working perfect.

只使用这两行,它工作完美。

jQuery('#select_selector').change(function(){
  jQuery("#select_selector1 option").eq(jQuery(this).find(':selected').index()).prop('selected',true);
});