MWO
MWO

Reputation: 2806

Dropdown remove blank item from list

I use this in haml to make a dropdown. I want to have the blank item before clicking (default nothing selected) as it is, but I want to remove the blank item from the list as it's nothing to select again! Is it possible?

- sort_options = [{text: "Text0", id: 0}, {text: "Text1", id: 1}, {text: "", id: 2}]
= select_tag id='dropdown_sorter_tag', options_for_select(sort_options.collect{ |k| [k[:text], k[:id]] }, sort_options.collect{ |k| [k[:text], k[:id]] }[2])

Upvotes: 1

Views: 337

Answers (1)

dtsuji
dtsuji

Reputation: 36

hmm, It's difficult specification 🤔

How is this code?

HTML

  <% sort_options = [{text: "Text0", id: 0}, {text: "Text1", id: 1}] %>
  <%= select_tag id='dropdown_sorter_tag', options_for_select(sort_options.collect{ |k| [k[:text], k[:id]] }, sort_options.collect{ |k| [k[:text], k[:id]] }[2]), include_blank: true %>

js(ES6)

const selectElement = document.querySelector('#dropdown_sorter_tag')

selectElement.addEventListener('change', (e) => {
  if (!selectElement.value) {
    return
  }
  const options = selectElement.querySelectorAll('option')
  for (let i = 0; i < options.length; i += 1) {
    if (options[i].value) {
      continue
    }
    options[i].remove()
  }
})

Upvotes: 1

Related Questions