Extract options from drop down list and display them as links


#1

Hi there,

I have the following select form:

<select class="single-option-selector" data-option="option2" id="product-select-11824419468productproduct-template-option-1">
<option value="Small (10)">Small (10)</option>
<option value="Medium (12)">Medium (12)</option>
<option value="Large (14)">Large (14)</option>
</select>

What I am trying to do is to extract each option, so they become buttons/links but keeping them as options within the select.

Is this possible?

Thanks


#2

Something like this?

<select class="single-option-selector">
  <option value="Small (10)">Small (10)</option>
  <option value="Medium (12)">Medium (12)</option>
  <option value="Large (14)">Large (14)</option>
</select>

<div class="button-group"></div>

const select = document.querySelector('.single-option-selector')
const options = Array.from(select.children)
const buttonGroup = document.querySelector('.button-group')

// Create buttons for each option with corresponding values
// and text content
options.forEach(({ value, textContent }) => {
  const button = document.createElement('button')

  button.textContent = textContent
  button.value = value
  button.type = 'button'

  buttonGroup.appendChild(button)
})

// When clicking a button, set the value of the select
// to the value of the button
buttonGroup.addEventListener('click', ({ target }) => {
  const { value, type } = target

  if (type === 'button') {
    select.value = value
  }
})

fiddle

Although I guess a radio group would be a better choice here to reflect the select behaviour (you might also hide the actual radio and only style their labels like buttons)... so you can also style the currently :checked one with CSS.


#3

Hi there,

Yes, that is exactly what I mean't. I guess I could use radio buttons, but I think that is what I am looking for.

Thanks for your help!


#4

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