Suleman khan
Suleman khan

Reputation: 1068

on selected value populating the dropdown list

I am having list of directories those are themes that has templates in it. I am listing the themes dropdown with list of themes when any theme get selected it will populate the other dropdown list with its(the selected theme's) templates.

here is my javascript code I am able to get the list of templates after selecting theme but when I am trying to change it, it is duplicating the values in the templates dropdown list.

$('#theme').on('change', function() {
  var selectedTheme = $(this).find('option:selected').val();
  $.ajax({
    url: '/admin/content/templates?theme=' + selectedTheme,
    type: 'GET',
    dataType: 'json',
    contentType: "application/json",
    data: JSON.stringify(selectedTheme),
    success: function(data) {
      console.log(data)
      $.each(data, function(idx, value) {
        $('#template').append('<option>' + value + '</option>');            
      });
    },
    error: function(data) {
      console.log("There are some errors")
    }
  });
});

here is my controller method to get the templates of a theme.

// getting the list of available templates
    @RequestMapping(value="/templates", produces="application/json")
    @ResponseBody
    List<String> getTemplates(@RequestParam("theme") String theme) {
        String path = "src/main/webapp/WEB-INF/views/themes/" + theme
        List<String> templates = []
        new File(path).eachFileMatch(~/.*.twig/) { file->
            file.path
            templates.add(file.getPath())
        }
        templates
    }

can anyone tell me why it is duplicating the values in the templates dropdown list ?

Upvotes: 0

Views: 72

Answers (2)

Trace
Trace

Reputation: 18899

You can store the data in a string and dump it with html:

  var str = ""; 
  $.each(data, function(idx, value) {
    str += '<option>' + value + '</option>';            
  }); 
  $('#template').html(str); 

I assume this would be more performant compared to writing on every loop.

Upvotes: 1

jwatts1980
jwatts1980

Reputation: 7354

Try adding a line to clear the template dropdown before repopulating it:

success: function(data) {
      console.log(data)
      $('#template').empty(); //<======
      $.each(data, function(idx, value) {
        $('#template').append('<option>' + value + '</option>');            
      });
    },

Upvotes: 1

Related Questions