user3224142
user3224142

Reputation: 61

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

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

Upvotes: 2

Views: 36268

Answers (5)

Wajahat Bashir
Wajahat Bashir

Reputation: 101

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

Upvotes: 0

Chay22
Chay22

Reputation: 2894

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

Upvotes: 8

Brett Gregson
Brett Gregson

Reputation: 5913

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

Upvotes: 2

Muhammad Umar
Muhammad Umar

Reputation: 348

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/

Upvotes: 0

Related Questions