3

I want to create tabs out of dropdown option select, for e.g whenever I choose first option, then the ul element with data-name="test" should render - is this achievable only with css in any way? By default first should be selected

<select>
<option data-value="test" value="test">Test</option>
<option data-value="test1" value="tes1t">Test</option>

</select>


<ul data-name="test">
    <li>Item</li>
</ul>

<ul data-name="test1">
    <li>Item</li>
</ul>
Dave
  • 1
  • 1
  • 9
  • 38
  • In my opinion, you need javascript for this. – Maik Lowrey Dec 29 '21 at 18:23
  • is this can help you? https://stackoverflow.com/a/55085687/17716837 – Laaouatni Anas Dec 29 '21 at 18:36
  • @LaaouatniAnas will it now which value was exactly checked? – Dave Dec 29 '21 at 19:25
  • if use use `option[value="test"]:checked` it will choose only the option with the value of *test* – Laaouatni Anas Dec 29 '21 at 19:27
  • but I think is best to use javascript at this point, because ~ combinator, don't work for elements outside... so we can style only the element itself but the list no ---- I will try to do it with javascript and put a answer – Laaouatni Anas Dec 29 '21 at 19:29
  • I tried my best https://jsfiddle.net/0fxcoy2j/ it work but not automatically check if dataname == datavalue :(, I hope someone will find this question and help you... I will upvote it so more people can find it – Laaouatni Anas Dec 29 '21 at 20:30

1 Answers1

1

If you need a CSS-only solution, you can use CSS pseudo-elements :valid and :invalid. But in this case you are limited to two options. Example below:

ul {
  display: none;
}

select:invalid ~ ul[data-name="test1"],
select:valid ~ ul[data-name="test2"] {
  display: block;
}
<select required>
  <option value="">Test</option>
  <option value="visible">Test2</option>
</select>

<ul data-name="test1">
  <li>Item 1</li>
</ul>

<ul data-name="test2">
  <li>Item 2</li>
</ul>

However, it is better to implement this in JavaScript, because you have a more flexible and understandable solution. Example below:

const checkElement = (id) => {
  document
    .querySelectorAll("ul")
    .forEach((el) => (el.hidden = el.dataset["name"] !== id));
};

document
  .querySelector("select")
  .addEventListener("change", (ev) => checkElement(ev.target.value));

checkElement("test1"); // set default element id
<select>
  <option value="test1">Test1</option>
  <option value="test2">Test2</option>
</select>

<ul data-name="test1" hidden>
  <li>Item 1</li>
</ul>

<ul data-name="test2" hidden>
  <li>Item 2</li>
</ul>

I hope these simple examples can help you somehow.

Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17