最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change dropdown value when another dropdown selected in a form using JQuery & ajax post - Stack Overflow

programmeradmin11浏览0评论

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

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

<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

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

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

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

<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

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

Share Improve this question edited Jan 23, 2016 at 9:35 user3224142 asked Jan 23, 2016 at 9:25 user3224142user3224142 611 gold badge1 silver badge7 bronze badges 5
  • use ajax for doing this. w3schools.com/jquery/jquery_ajax_intro.asp – ameenulla0007 Commented Jan 23, 2016 at 9:28
  • Use jQuery.ajax() to make a request to the server where you send the county ID, return the provinces for that country and set the options for the the second drop down. Repeat for cities – Brett Gregson Commented Jan 23, 2016 at 9:29
  • @eskimo how do I send the data from dropdown of country? do that dropdown need its own form to send a value to server? can you please write ajax post for country so it can send its value to server? thank you – user3224142 Commented Jan 23, 2016 at 9:35
  • 1 You need to break what you're trying to accomplish down into steps. Step one is use jQuery.ajax to send a select value to the server. Step two is return a value from the server as JSON. Step three is update a selects options with JSON. Nobody is going to write the code for you, there are a million examples of each of these steps online – Brett Gregson Commented Jan 23, 2016 at 9:38
  • @eskimo that's exactly steps that I am trying to accomplish, can you please point me to an articles? I don't know the keyword to find this – user3224142 Commented Jan 23, 2016 at 9:54
Add a comment  | 

5 Answers 5

Reset to default 8

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

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

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

First add an id to your province select and your city 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:

<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.php script which you are calling with 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.php to 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

Please check this tutorial. it will definitely help you.

http://www.php-dev-zone.com/2013/10/country-state-city-dropdown-using-ajax.html

Or this one.

http://www.techsofttutorials.com/ajax-country-state-city-dropdown-using-phpmysql/

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

    $(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/

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论