0

I'm trying to create a dropdown which populates the list based on the option selected in the previous dropdown, but the second dropdown is somehow not working. Here i found a site http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html which is exactly what i want but it's not working for me. It's working separately but when i add it into my existing code it's not working. Please help!

Baba Sai
  • 1
  • 1
  • Welcome to Stack Overflow! You can take the [tour] first and learn [ask] a good question and create a [mcve]. That makes it easier for us to help you. – Katie Feb 04 '17 at 16:26

1 Answers1

0

I think this is what you are looking for, test it out below and let me know.

var countries = [{id: 1, name: "United States"}, {id: 2, name: "Canada"}, {id: 3, name: "United Kingdom"}, {id: 4, name: "France"}];

var states = [{id: 1, country_id: 1, name: "OH"}, {id: 2, country_id: 1, name: "NY"}, {id: 3, country_id: 2, name: "Montreal"}, {id: 4, country_id: 2, name: "Ontario"}, {id: 5, country_id: 3, name: "Scotland"}, {id: 6, country_id: 3, name: "Ireland"}, {id: 7, country_id: 4, name: "Normandy"}];

var option = '';
$.each(countries, function( index, value ) {
   option += '<option value="'+ value.id + '">' + value.name + '</option>';
});

$('#country').append(option);

$('#country').on('change', function (e) {
    var id = $(this).val();
    $('#state').empty()
    var results = $.grep(states, function(e){ return e.country_id == id; });
  var stateOptions = '';
  $.each(results, function( index, value ) {
     stateOptions += '<option value="'+ value.id + '">' +     value.name + '</option>';
  });

   $('#state').append(stateOptions);
});

$('#country').trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="country">

</select>

<select id="state">

</select>
  • Hello thanks for the quick response. Actually i'm using PHP to populate the select options list. So can you tell me a way without using arrays. – Baba Sai Feb 05 '17 at 11:45
  • I do not know php well enough to help with that. I would try looking at this answer http://stackoverflow.com/questions/2460243/using-php-to-populate-a-select-select. If somebody else knows how to do do this could they please edit this answer? –  Feb 05 '17 at 16:23