Selecting a select from a div and label above it

Hi,

I’m trying to select based on a label and a div above it, but I can’t figure it out.

This is my HTML:

<div class="select">
        <label>Colour</label>
        <div class="selector-wrapper">
          <select>
             <option value="1">1</option>
          </select>
      </div>

and this is the jQuery i’m trying to use:

$('label:contains("Colour")').nextAll('div:has(select)').prepend('<option value="Select Color" selected="selected" disabled>Select Colour</option>');

Any ideas what I have wrong?

Thank you.

So you’re trying to populate the select from the labels? With what form controls would those labels actually be associated then? I mean there’s a lot hard-coded data in your JS that would probably better be inferred from the markup, such as the values of those control elements or data-* attributes. Same with the selector – don’t query for elements by their content; this is error prone as you’d have to adjust the JS whenever you change the wording (not to mention adding translations).

Anyway it looks like you’re prepending the option to the wrapper div, not the actual select… the best solution would be to simply give that select an ID:

<label class="option-label" data-option="Select colour" for="?">Colour</label>
<label class="option-label" data-option="Select size" for="?">Size</label>

<div class="selector-wrapper">
  <select id="my-select"></select>
</div>
const $mySelect = $('#my-select')

$('.option-label').each((index, element) => {
  $('<option />', { value: index })
    .text(element.dataset.option)
    .appendTo($mySelect)
})

Hi,

Yes I’m trying to populate the select from the the label. The problem I have is that some of the fields are set up differently. For example, some selects are just under a label, whereas some are under a div which is under a label. It’s a huge script so now, that’s why i’m trying to modify it that way.

As I said, just give them IDs then and this doesn’t matter. If you want to populate multiple selects you might als store the target selector in a data-* attribute like so:

<label 
  data-select="#my-select" 
  data-option="Select colour" 
  for="?"
>Colour</label>

<label 
  data-select="#my-select" 
  data-option="Select size" 
  for="?"
>Size</label>

<div class="selector-wrapper">
  <select id="my-select"></select>
</div>
$('[data-select]').each((index, element) => {
  const $select = $(element.dataset.select)

  $('<option />', { value: index })
    .text(element.dataset.option)
    .appendTo($select)
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.