-1

I wanna make a dependable dropdown but I can't reach the child dropdown with jQuery:

These are the elements:

var types = $('#categorias').next('div').next('select[name="type_id"]').html();
console.log(types);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
  <label for="category_id">Categoría</label>
  <select id="categorias" class="form-control" name="category_id">
    <option value="">Elegir categoría: </option>
    <option value="1">Frutas y verduras</option>
    <option value="2">Alimentos a granel</option>
    <option value="3">Alimentos envasados</option>
    <option value="4">Bebidas</option>
    <option value="5">Art. de aseo personal</option>
    <option value="6">Art. de limpieza</option>
  </select>
</div>
<div class="form-group">
  <label for="type_id">Tipo de producto</label>
  <select name="type_id" class="form-control">
    <option>Elegir tipo de producto: </option>
    <option value="1">Tomate</option>
    <option value="2">Plátano</option>
    <option value="3">Naranja</option>
    <option value="4">Manzana</option>
    <option value="5">Palta</option>
    <option value="6">Papa</option>
    <option value="7">Spaghetti 5</option>
    <option value="8">Cabello de Ángel</option>
  </select>
</div>

I can't reach the code of the second dropdown to remove all the options from it and repopulate it with the new options.

I'm trying:

$('#categorias').first().closest('div').next('select[name="type_id"]');

but all I get is undefined or an empty set.

EDIT: I should clarify that this is just one select within a group of forms that can be created dynamically so I just want to reach the next one without accidentally removing several of them or having to add them individual ids.

ffuentes
  • 1,042
  • 5
  • 16
  • 36
  • just give it an id and `document.getElementById()`.. you dont need to do crazy queries to find the element. – Isaac Vidrine May 20 '19 at 20:13
  • `.next('div')` selects the next element if it's a div. `$('#categorias').next('div')` doesn't exist. You need to go *up* the DOM first. See parent() and closest(). Also `$('#categorias').first()` doesn't make sense as IDs must be unique, so why use `first()`? – j08691 May 20 '19 at 20:16
  • Take a look at https://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-as-a-js-object-with-jquery – Woodrow May 20 '19 at 20:17
  • Why do you need to use `.next()`? Are there multiple `select[name=type_id]` elements in the DOM, and you only want to select the one immediately after `#categorias`? – Barmar May 20 '19 at 20:18

1 Answers1

3

To go from one select to the next one use the format:

$('select').closest('div.form-group').next('div.form-group').find('select')

.closest() traverses up the DOM, and .find() down.

j08691
  • 204,283
  • 31
  • 260
  • 272