Dynamic Selects

1

I wonder if you can create dynamic selects on a page, identical to the free market signup.

Actually, I'm trying to create an integration exactly with their routine. I'm having difficulty with the categories. Depending on the type of the parent category, it is necessary to open a new select with the child categories and so on. There is no way to know the number of items or hierarchy.

I made the select from the main category, like this:

<div id="categoria">
<label>Categoria</label>
<select id="cmbCategoria" class="sub">
    <option>Carregar Categoria</option>
</select>
<input type="button" value="Carregar Categoria" id="btnCategoria" class="botao"/>
</div>

As I researched, to include a select would look like this:

$("#categoria" ).append("<select class='sub' id="+id+"><option value>Subcategoria</option></select>");

Would it be any easier? Can I get the dynamic select id?

    
asked by anonymous 31.03.2018 / 04:03

1 answer

0

If this <select> is being dynamically mounted and you want to add more items "dynamically", you should look for the element dynamically:

let categorias = [
   {
      id: 001,
      value: 'imoveis'
   },
   {
      id: 002,
      value: 'carros'
   },
   {
      id: 003,
      value: 'celulares'
   },
   {
      id: 004,
      value: 'computadores'
   }
]

// primeira iteração (adicionar categoria(s))
categorias.forEach(item => {
    $('#select').append('<optgroup id="${item.id}" label="${item.value}"></optgroup>')
})

// segunda iteração (adicionar itens a elementos dinamicos)
categorias.forEach(item => {
    $('#'+item.id).append('
        <option>item 001</option>
        <option>item 002</option>
        <option>item 003</option>
    ')
})
        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="select"></select>

If you know the structure of the data you should simply map it and iterate. This data can come from a JSON ai just do the parse ( JSON.parse() ) if it is an array already available in the front-end (javascript) just scroll through it.

This example is simple and distributes in groups, even if your solution uses a "custom" select the logic should be the same.

    
31.03.2018 / 04:23