J888
J888

Reputation: 1964

How to populate a dropdown list based on values of the another list?

I want to implement a search box same as this, at first, just first dropdown list is active once user selects an option from the first dropbox, the second dropdown box will be activated and its list will be populated.

<s:select id="country" name="country" label="Country" list="%{country} onchange="findCities(this.value)"/>

<s:select id="city" name="city" label="Location" list=""/>

Upvotes: 3

Views: 3241

Answers (7)

Nick Charney Kaye
Nick Charney Kaye

Reputation: 4340

IMO this is the base case AngularJS was designed to completely alleviate. Check it out!

Upvotes: 0

grateful
grateful

Reputation: 1128

You seem to be asking two questions:

QUESTION 1. How to have a disabled select box (the second and third select boxes in the case of your example) which is activated upon the selection of an option from the first select box.

ANSWER 1: simply use the disabled=true/false as below...

<select id="country" name="country" label="Country" onchange="document.getElementById('city').disabled=false; findCities(this.value)"/> <select id="city" name="city" label="Location" disabled=true/>

NOTE: I changed "s:select" to "select" on the basis that your question does not make reference or tag the Struts framework that uses this syntax.

QUESTION 2: How to populate the second select box when a selection is made in the first.

ANSWER 2: There are many ways to do this, and the choice depends on where you have the data to populate the lists with. In the case of your Rentalcars example, if you chose Barbados, the browser sends an ajax GET request to "http://www.rentalcars.com/AjaxDroplists.do;jsessionid=5DCBF81333A88F37BC7AE15D21E10C41.node012a?country=Barbados&wrapNonAirports=true" -try clicking on this link and you will see what that request is sending back. This '.do' address is a server side file of a type used with the Struts framework I mentioned above.

A more conventional approach, which would be included in your function findCities(country)would be to send an AJAX request to a PHP script which queries a database and sends back an array of place names to the browser. The AJAX javascript code includes instructions as to what to do with the response. Without knowing more about where you want to store your list, giving an example of this would most likely not be useful.

Alternatively, the whole list of places could be included in the javascript script as an array (as demonstarated by Devima, above), in a text document on the server as comma separated values, or you could save it to a browser database like WebSQL or IndexedDB if offline use would be useful.

When you have got your list, probably as an array of values, you could save the array as a variable eg. var cities=result (in the case of a simple ajax request). You will then need to iterate through cities, for example

for (var i = 0; i < cities.length; i++){
var place=cities[i];//an individual city name
document.getElementById("city").innerHTML+="<option value='" + place + "'>" + place + "</option>";//adds an 'option' with the value being the city name and the text you see being the city name
}

Upvotes: 0

Kshitiz
Kshitiz

Reputation: 2743

Hi i have done this for license and its dependent subject in yii 1. The license dropdown //php code foreach($subject as $v) { $subj .= $v['licenseId'] . ":" . $v['subjectId'] . ":" . $v['displayName'] . ";"; } Yii::app()->clientScript->registerScript('variables', 'var subj = "' . $subj . '";', CClientScript::POS_HEAD); ?>

//javascript code
jQuery(document).ready(function($) {

    //subject. dependent dropdown list based on licnse
    var ty, subjs = subj.split(';'), subjSel = []; //subj register this varible from php it is


  for(var i=0; i<subjs.length -1; i++) { //-1 caters for the last ";"
    ty = subjs[i].split(":");
    subjSel[i] = {licId:ty[0], subjId:ty[1], subjName:ty[2]};
  }

    //dropdown license
  jQuery('#license#').change(function() {
    $('#add').html(''); //clear the radios if any

    val = $('input[name="license"]:checked').val();
    var selectVals = "";
        selectVals += '<select>';

    for(var i=0; i<subjSel.length; i++) {
      if(subjSel[i].licId == val) {
        if(subjSel[i].subjId *1 == 9) continue;
        selectVals += '<option value="'+subjSel[i].subjId+'">'+subjSel[i].subjName+'</option>';
      }
    }
        selectVals += '</select>';

    $("#subject").html(selectVals);
  });
});

Upvotes: 0

Devima
Devima

Reputation: 1566

Ciao j888,
in this fiddle i tried to reconstruct the same system as the site you provided the link
the number of states cityes and locality is less but the concept remains the same
If you want to add a new state you must enter a new html options in select#paese with an id.
Then you have add in obj.citta a property with this id name and an array of cityes for a value.
The same thing for obj.localita where you will create an array of arrays. The jQuery code you need is

<script type="text/javascript">
$(document).ready(function(){
    var obj={
        citta:{ //value is the same of option id
            albania:['Durres','Tirana'],
            austria:['Vienna','innsbruck','Graz'],
            },
        localita:{//for every city create a sub array of places
            albania:[['località Durres1','località Durres 2'],['località Tirana','località Tirana 2']],
            austria:[['località Vienna','località Vienna 2'],['località innsbruck','località innsbruck 2'],['località Graz','località Graz 2','località Graz 3']],
            }   
        }

    $('#paese').on('change',function(){
        $('#località').attr('disabled','disabled').find('option').remove()
        var quale=$(this).find('option:selected').attr('id')
        var arr=obj.citta[quale]
        if(arr){
            $('#citta').removeAttr('disabled')
            $('#citta option.added').remove()
            for(i=0;i<arr.length;i++){
                $('<option class="added">'+arr[i]+'</option>').appendTo('#citta')
                }
            }
        })

    $('#citta').on('change',function(){
        var ind=($(this).find('option:selected').index())-1
        var quale=$('#paese').find('option:selected').attr('id')
        var arr=obj.localita[quale][ind]
        if(arr){
            $('#località').removeAttr('disabled')
            $('#località option.added').remove()
            for(i=0;i<arr.length;i++){
                $('<option class="added">'+arr[i]+'</option>').appendTo('#località')
                }
            }
        })

})
</script>

If this solution does not suit your needs, i apologize for making you lose time.

Upvotes: 0

laaposto
laaposto

Reputation: 12213

Try this code where based on your needs you have to populate it with your options:

var x;

$('#pu-country').on('change', function () {
    if (this.value != '0') {

        $('#pu-city').prop('disabled', false);
        $('#pu-city').find("option").not(":first").remove();
        $('#pu-location').prop('disabled', true);
        $('#pu-location').val("Choose");

        switch (this.value) {
            case 'A':
                x = '<option value="A.1">A.1</option><option value="A.2">A.2</option><option value="A.3">A.3</option>'
        }
        $('#pu-city').append(x)
    } else {
        $('#pu-location').prop('disabled', true);
        $('#pu-location').val("Choose");
        $('#pu-city').prop('disabled', true);
        $('#pu-city').val("Choose");
    }


});

$('#pu-city').on('change', function () {
    if (this.value != '0') {

        $('#pu-location').prop('disabled', false);
        $('#pu-location').find("option").not(":first").remove();

        switch (this.value) {
            case 'A.1':
                x = '<option value="A.1.1">A.1.1</option><option value="A.1.2">A.1.2</option><option value="A.1.3">A.1.3</option>'
                break;
            case 'A.2':
                x = '<option value="A.2.1">A.2.1</option><option value="A.2.2">A.2.2</option><option value="A.2.3">A.2.3</option>'
                break;
            case 'A.3':
                x = '<option value="A.3.1">A.3.1</option><option value="A.3.2">A.3.2</option><option value="A.3.3">A.3.3</option>'
                break;

        }

        $('#pu-location').append(x)
    } else {
        $('#pu-location').prop('disabled', true);
        $('#pu-location').val("Choose");
    }


});

I have also set up and a demo to see the functionallity with more options.

FIDDLE

Upvotes: 1

Pramod S. Nikam
Pramod S. Nikam

Reputation: 4539

Jquery chained plugin will serve your purpose,

https://plugins.jquery.com/chained/

usage link - http://www.appelsiini.net/projects/chained

this plugin will chain your textboxes.

Upvotes: 1

Saggex
Saggex

Reputation: 3500

Your code should be something like this:

$(country).change(function(){
var l=Document.getElementByID("country"); 
for(i=0;i<=l.length;i++)
    {
    if(l.options[i].selected?)
       {
       text_array=[HERE YOU NEED TO ADD THE CITIES OF l.options[i].text];
       val_array=[HERE YOU NEED TO ADD THE VALUES OF THECITIES OF l.options[i].text];
       }
    }
var c=Document.getElementByID("city"); 
    c.options.text=[];
    c.options.value=[];
//You now should have an empty select.
    c.options.text=text_array ;
    c.options.value=val_array ;
});

As I don't know, what kind of DB you use, to have the cities connected to their countrys, I can't tell you, what to put into the uppercase text...

Upvotes: 0

Related Questions