Skip to content Skip to sidebar Skip to footer

Converting Javascript Array To A Dropdown - Jquery

I wanted to create dynamic dropdowns in which the values are changed based on the first dropdown. Suppose I have a dropdown with three values namely One, Two and Three. When I sele

Solution 1:

this could be improved upon, but this should point you in the right direction. Here's the js fiddle

<scriptsrc='jquery.js'></script><selectclass="dropdown"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select><selectclass="dropdown2"></select><script>
$(document).ready(function() {
  var dropdown2 = {
    1 : ['Four', 'Five', 'Six'],
    2 : ['Seven', 'Eight', 'Nine'],
    3 : ['Ten', 'Eleven', 'Twelve']
  }
  $('.dropdown').on('change',function() {
    $('.dropdown2').html(
      '<option>'+dropdown2[$(this).val()].join('</option><option>')+'</option>'
    );
  });
});
</script>

Solution 2:

http://jsfiddle.net/tcTwL/5/

var data = {
    one: ['Four', 'Five', 'Six'],
    two: ['Seven', 'Eight', 'Nine'],
    three: ['Ten', 'Eleven', 'Twelve']
}

$('.dropdown').change(function () {
  $('.dropdown2').remove();
  var newSel = $(this).after('<select class="dropdown2" />'); 
  var option = $('.dropdown').find(":selected").text();
  data[option.toLowerCase()].forEach(function(opt){$('.dropdown2').append('<option>' + opt + '</option>')});
})

Fairly straightforward. remove any older dropdown created, get the option value, and add new options. It's kinda verbose, but it works.

Solution 3:

Check this demo jsFiddle

jQuery

$(document).ready(function() {
    var dropdown1 = {
        1 : ['Four', 'Five', 'Six'],
        2 : ['Seven', 'Eight', 'Nine'],
        3 : ['Ten', 'Eleven', 'Twelve']
    }
    $('.dropdown1').html(
            '<option>'+dropdown1[1].join('</option><option>')+'</option>'
        );
    $('.dropdown').on('change',function() {
        $('.dropdown1').html(
            '<option>'+dropdown1[$(this).val()].join('</option><option>')+'</option>'
        );
    });
});

HTML

<selectclass="dropdown">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<selectclass="dropdown1">
    

Post a Comment for "Converting Javascript Array To A Dropdown - Jquery"