stephenthedev
stephenthedev

Reputation: 577

Improve Dynamic Dropdown Solution

I've created a dynamic dropdown list with jQuery and JavaScript. I'm hoping someone can take a look and let me know if this is an appropriate way to handle this type of task. I'm specifically curious to know if this code is scalable, and will it perform well? Next, would it be suggested to use a switch statement instead of several if statements in the JavaScript I have below? If so, why? I'd like to store this to be reused anytime I implement a solution like this, but as I'm new to JavaScript I don't completely trust my work yet.

JSFIDDLE: http://jsfiddle.net/6vrpF/

HTML:

<select id='parent'>
  <option value='test'>test</option>
  <option value='sure'>sure</option>
  <option value='cool'>cool</option>
  <option value='best'>best</option>
</select>

<select id='child'>
</select>

JavaScript:

function newDropdown()
{
   var html = ""
   for(i=0; i<arguments.length; i++)
   {
     html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
   }
   $("#child").append(html)
}

$("#parent").on("change",function(){
  $('#child').text("")
  var selection = $("#parent").val()
  if(selection == 'test') {newDropdown('a','b','c')}
  if(selection == 'sure') {newDropdown('d','e','f')}
  if(selection == 'cool') {newDropdown('g','h','i')}
  if(selection == 'best') {newDropdown('j','k','l')}
});

Upvotes: 0

Views: 136

Answers (1)

ripu1581
ripu1581

Reputation: 300

updated the fiddle http://jsfiddle.net/6vrpF/4/

var parentChild = {
    "test" :['a','b','c'],
    "sure" :['d','e','f'],
    "cool" :['g','h','i'],
    "best" :['j','k','l']
};

function newDropdown()
{
    var html = ""
    for(i=0; i<arguments.length; i++)
    {
        html += "<option value='"+arguments[i]+"'>"+arguments[i]+"</option>"
    }
    $("#child").append(html)
}

$("#parent").on("change",function(){
    $('#child').text("")
    var selection = $("#parent").val();
    newDropdown( parentChild[selection].join(",") );
});

You need to get your data in the JSON format as mentioned/defined above

Edit: this is the updated fiddle which will give options one by one http://jsfiddle.net/6vrpF/6/

var parentChild = {
    "test" :['a','b','c'],
    "sure" :['d','e','f'],
    "cool" :['g','h','i'],
    "best" :['j','k','l']
};

function newDropdown()
{
    var array = arguments[0];
    var html = ""
    for(i=0; i<array.length; i++)
    {
        html += "<option value='"+array[i]+"'>"+array[i]+"</option>"
    }
    $("#child").append(html)
}

$("#parent").on("change",function(){
    $('#child').text("")
    var selection = $("#parent").val();
    newDropdown( parentChild[selection] );
});

Upvotes: 2

Related Questions