Dynamic selects

Asked

Viewed 66 times

1

I would like to know if it is possible to create dynamic selects on a page, identical to the free market advertising register.

In fact, I’m trying to create an integration with exactly their routine. I’m having difficulties 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 nor the hierarchy.

I selected the main category that way:

<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>

From what I’ve researched, to include a select would be that way:

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

Would there be an easier way? I can get the id of the dynamic select?

  • The idea seems right, but where will you pull this data? Via Ajax?

  • Ideally you would already leave this data saved in a variable in Javascript, so you would save your server resources, and display it in HTML according to what the user was selecting.

1 answer

0

If this <select> is being mounted dynamically and you want to add more items "dynamically", you should search 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>


<select id="select"></select>

If you know the data structure you should simply map and iterate it. This data may come from a JSON Then just do the parse (JSON.parse()) if it is an array already available on the front end (javascript) just go through it.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.