从下拉菜单中删除先前选项中的已选类 JavaScript

huangapple go评论65阅读模式
英文:

Remove selected class from previous option in dropdown javascript

问题

我有一个下拉选择选项和一些按钮,它们都包含相同的值。

当我从下拉菜单中选择一个选项时,我希望具有相同值的按钮添加一个名为“selected”的类,当我从下拉菜单中选择另一个选项时,我希望将“selected”类从以前的选择中移除,并添加到新值上。

目前,我只能让它显示一个名为“selected”的类,但一旦我选择了新的选项,它就无法从以前的选项中移除这个类,有谁知道如何做到这一点吗?

我只想使用纯JS,不要使用jQuery。

以下是您提供的代码:

英文:

I have both a dropdown select option and some buttons both containing the same values.

When I select an option from my dropdown I want the button with the same value to add a class of selected and when I select another option from my dropdown I want it to remove the class of selected from the previous selection and add it to the new value.

For now I've only managed to get it to show a class of selected but it won't remove this class from the previous option once I've selected a new one, does anyone know how I go about doing this please?

I only want to use vanilla JS for this, no jQuery please.

code below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const btn = document.querySelectorAll(&quot;.btn-num&quot;);
const dropDown = document.querySelector(&#39;#dropdown-container .dropdown&#39;);

dropDown.addEventListener(&quot;change&quot;, function(){
    btn.forEach(x =&gt; {
        if (x.getAttribute(&#39;data-value&#39;) == this.value) {
            x.classList.add(&#39;selected&#39;);
        }
    });
});

<!-- language: lang-css -->

.btn-num.selected {
  background-color: green;
  color: #fff;
}

<!-- language: lang-html -->

&lt;div id=&quot;dropdown-container&quot;&gt;    
    &lt;select class=&quot;dropdown&quot;&gt;       
        &lt;option value=&quot;&quot; selected=&quot;&quot; disabled=&quot;&quot;&gt;Numbers&lt;/option&gt;
        &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
        &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
        &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
        &lt;option value=&quot;4&quot;&gt;4&lt;/option&gt;
    &lt;/select&gt;
&lt;/div&gt;

&lt;div class=&quot;options&quot;&gt;
    &lt;div class=&quot;btn-num&quot; data-value=&quot;1&quot;&gt;
        1
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;2&quot;&gt;
        2
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;3&quot;&gt;
        3
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;4&quot;&gt;
        4
    &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

你忘了移除类。使用 x.classList.remove()

document.querySelector(".selected")?.classList.remove("selected")
英文:

You forgot to remove class. Use x.classList.remove()

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const btn = document.querySelectorAll(&quot;.btn-num&quot;);
const dropDown = document.querySelector(&#39;#dropdown-container .dropdown&#39;);

dropDown.addEventListener(&quot;change&quot;, function() {
    btn.forEach(x =&gt; {
        x.classList.remove(&#39;selected&#39;); 
        if (x.getAttribute(&#39;data-value&#39;) == this.value) {
            x.classList.add(&#39;selected&#39;); 
        }
    });
});

<!-- language: lang-css -->

.btn-num.selected {
  background-color: green;
  color: #fff;
}

<!-- language: lang-html -->

&lt;div id=&quot;dropdown-container&quot;&gt;    
    &lt;select class=&quot;dropdown&quot;&gt;       
        &lt;option value=&quot;&quot; selected=&quot;&quot; disabled=&quot;&quot;&gt;Numbers&lt;/option&gt;
        &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
        &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
        &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
        &lt;option value=&quot;4&quot;&gt;4&lt;/option&gt;
    &lt;/select&gt;
&lt;/div&gt;

&lt;div class=&quot;options&quot;&gt;
    &lt;div class=&quot;btn-num&quot; data-value=&quot;1&quot;&gt;
        1
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;2&quot;&gt;
        2
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;3&quot;&gt;
        3
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;4&quot;&gt;
        4
    &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

If you wanted to remove class only from the currently .selected item us can us ?. syntax is used to check if element .selected exists and remove the class only form the specific element
:

document.querySelector(&quot;.selected&quot;)?.classList.remove(&quot;selected&quot;)

答案2

得分: 0

要删除selected类,只需在条件检查之前添加x.classList.remove('selected');

英文:

To remove the selected class you just need to add x.classList.remove(&#39;selected&#39;); right before your conditional check.

答案3

得分: 0

我不太确定,但我认为这段代码可能有效,其中使用 **x.classList.remove('selected')** 从所有按钮中移除“selected”类。然后,仅将“selected”类添加到其 **'data-value'** 属性与下拉菜单中新选择的选项相匹配的按钮,使用 **x.classList.add('selected')** 而不是移除,当然:

```plaintext

<details>
<summary>英文:</summary>

I&#39;m not quite sure, but I think this piece of code could work, where the &quot;selected&quot; class is being removed from all buttons using **x.classList.remove(&#39;selected&#39;).** Then adding &quot;selected&quot; class only to button whos **&#39;data-value&#39;** attr. matches the newly selected option in the dropdown, using the &#39;**x.classList.add(&#39;selected&#39;)** instead of the remove, of course:

    const btn = document.querySelectorAll(&quot;.btn-num&quot;);
    const dropDown = document.querySelector(&#39;#dropdown-container .dropdown&#39;);
    
    dropDown.addEventListener(&quot;change&quot;, function(){
        btn.forEach(x =&gt; {
            x.classList.remove(&#39;selected&#39;);
            if (x.getAttribute(&#39;data-value&#39;) == this.value) {
                x.classList.add(&#39;selected&#39;);
            }
        });
    });

This should help you get the desired functionality where only one button has the &quot;selected&quot; class at any given time, and it corresponds to the currently selected option in the dropdown.

Hope this helps! :)

</details>



# 答案4
**得分**: 0

这是代码示例,不需要翻译:

```javascript
const dropDown = document.querySelector('.dropdown'),
      dropDownOptions = dropDown.querySelectorAll('option'),
      optionsContainer = document.querySelector('.options'),
      optionsDisplay = optionsContainer.querySelectorAll('.btn-num')

dropDown.addEventListener('change', (e) => {

  const selectedOption = e.target.value
  
  optionsDisplay.forEach(option => {
  
    option.classList.remove('selected')
    
    if (option.dataset.value === selectedOption)
      option.classList.add('selected')
  
  })

})
main {
  padding: 2rem;
  display: grid;
  grid-auto-flow: row;
  gap: 2rem;
  font-family: monospace;
  font-weight: 900;
  font-size: 2rem;
}

#dropdown-container {
  background-color: hsl(156 75% 90%);
  padding: 1rem;
  border-radius: 1rem;
}

.options {
  background-color: hsl(287 75% 90%);
  padding: 1rem;
  border-radius: 1rem;
  display: flex;
  justify-content: space around;
  align-items: center;
}

.btn-num {
  padding: 0.25rem 0.75rem;
  background-color: black;
  color: hsl(287 75% 90%);
  border-radius: 0.5rem;
}

.btn-num.selected {
  background-color: white;
  color: hsl(287 75% 50%);
  box-shadow: 0 0.125rem 1rem hsl(215 50% 15% / 0.15);
  text-shadow: 0 0.125rem 0.5rem hsl(215 50% 15% / 0.5);
}
<main>

  <div id="dropdown-container">    
    <select class="dropdown">       
      <option value="" selected="" disabled="">Numbers</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
    </select>
  </div>

  <div class="options">
    <div class="btn-num" data-value="1">
      1
    </div>

    <div class="btn-num" data-value="2">
      2
    </div>

    <div class="btn-num" data-value="3">
      3
    </div>

    <div class="btn-num" data-value="4">
      4
    </div>
  </div>

</main>
英文:

It's fairly simple. Others explained it already. I wrote it slightly differently, but it doesn't make a difference. It's really just adding the classList.remove(&#39;selected&#39;) method. Maybe my version will help anyway.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const dropDown = document.querySelector(&#39;.dropdown&#39;),
      dropDownOptions = dropDown.querySelectorAll(&#39;option&#39;),
      optionsContainer = document.querySelector(&#39;.options&#39;),
      optionsDisplay = optionsContainer.querySelectorAll(&#39;.btn-num&#39;)
      
dropDown.addEventListener(&#39;change&#39;, (e) =&gt; {

  const selectedOption = e.target.value
  
  optionsDisplay.forEach(option =&gt; {
  
    option.classList.remove(&#39;selected&#39;)
    
    if (option.dataset.value === selectedOption)
      option.classList.add(&#39;selected&#39;)
  
  })

})

<!-- language: lang-css -->

main {
  padding: 2rem;
  display: grid;
  grid-auto-flow: row;
  gap: 2rem;
  font-family: monospace;
  font-weight: 900;
  font-size: 2rem;
}

#dropdown-container {
  background-color: hsl(156 75% 90%);
  padding: 1rem;
  border-radius: 1rem;
}

.options {
  background-color: hsl(287 75% 90%);
  padding: 1rem;
  border-radius: 1rem;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.btn-num {
  padding: 0.25rem 0.75rem;
  background-color: black;
  color: hsl(287 75% 90%);
  border-radius: 0.5rem;
}

.btn-num.selected {
  background-color: white;
  color: hsl(287 75% 50%);
  box-shadow: 0 0.125rem 1rem hsl(215 50% 15% / 0.15);
  text-shadow: 0 0.125rem 0.5rem hsl(215 50% 15% / 0.5)
}

<!-- language: lang-html -->

&lt;main&gt;

  &lt;div id=&quot;dropdown-container&quot;&gt;    
    &lt;select class=&quot;dropdown&quot;&gt;       
      &lt;option value=&quot;&quot; selected=&quot;&quot; disabled=&quot;&quot;&gt;Numbers&lt;/option&gt;
      &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
      &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
      &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
      &lt;option value=&quot;4&quot;&gt;4&lt;/option&gt;
    &lt;/select&gt;
  &lt;/div&gt;

  &lt;div class=&quot;options&quot;&gt;
    &lt;div class=&quot;btn-num&quot; data-value=&quot;1&quot;&gt;
      1
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;2&quot;&gt;
      2
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;3&quot;&gt;
      3
    &lt;/div&gt;

    &lt;div class=&quot;btn-num&quot; data-value=&quot;4&quot;&gt;
      4
    &lt;/div&gt;
  &lt;/div&gt;

&lt;/main&gt;

<!-- end snippet -->

答案5

得分: 0

为了缩短代码,使用 classList.toggle() 方法。

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const 
  btns     = document.querySelectorAll(".btn-num")
, dropDown = document.querySelector('#dropdown-container .dropdown')
  ;
dropDown.addEventListener("change", function() { 
  btns.forEach( bt =>
    bt.classList.toggle('selected', bt.dataset.value===this.value ));
});

<!-- language: lang-css -->
.btn-num.selected {
  background : green;
  color      : #fff;
}

<!-- language: lang-html -->
<div id="dropdown-container">    
    <select class="dropdown">       
        <option value="" selected="" disabled="">Numbers</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
</div>

<div class="options">
  <div class="btn-num" data-value="1"> 1 </div>
  <div class="btn-num" data-value="2"> 2 </div>
  <div class="btn-num" data-value="3"> 3 </div>
  <div class="btn-num" data-value="4"> 4 </div>
</div>

<!-- end snippet -->
英文:

for shorter code use classList.toggle() method

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const 
  btns     = document.querySelectorAll(&quot;.btn-num&quot;)
, dropDown = document.querySelector(&#39;#dropdown-container .dropdown&#39;)
  ;
dropDown.addEventListener(&quot;change&quot;, function() { 
  btns.forEach( bt =&gt;
    bt.classList.toggle(&#39;selected&#39;, bt.dataset.value===this.value ));
  });

<!-- language: lang-css -->

.btn-num.selected {
  background : green;
  color      : #fff;
  }

<!-- language: lang-html -->

&lt;div id=&quot;dropdown-container&quot;&gt;    
    &lt;select class=&quot;dropdown&quot;&gt;       
        &lt;option value=&quot;&quot; selected=&quot;&quot; disabled=&quot;&quot;&gt;Numbers&lt;/option&gt;
        &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
        &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
        &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
        &lt;option value=&quot;4&quot;&gt;4&lt;/option&gt;
    &lt;/select&gt;
&lt;/div&gt;

&lt;div class=&quot;options&quot;&gt;
  &lt;div class=&quot;btn-num&quot; data-value=&quot;1&quot;&gt; 1 &lt;/div&gt;
  &lt;div class=&quot;btn-num&quot; data-value=&quot;2&quot;&gt; 2 &lt;/div&gt;
  &lt;div class=&quot;btn-num&quot; data-value=&quot;3&quot;&gt; 3 &lt;/div&gt;
  &lt;div class=&quot;btn-num&quot; data-value=&quot;4&quot;&gt; 4 &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月7日 23:22:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定