Home > Software engineering >  how to filter by using value
how to filter by using value

Time:09-19

I want to hide .tab when I click .btn in another div. but this code doesn't work. I don't want to use filter by index for some reasons

How Can I fix it?

$(".btn").click(function() {
  var tabname = $(this).parent().attr("id")

  $(".tab").filter(function() {
    return $(this).attr("value") === tabname
  }).hide()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="tab01">
  <button > button</button>
</div>
<div id="tab02">
  <button > button</button>
</div>
<div id="tab03">
  <button > button</button>
</div>

<div >
  <button  value="#tab01">This is button 1</button>
  <button  value="#tab02">This is button 2</button>
  <button  value="#tab03">This is button 3</button>
</div>

CodePudding user response:

Basically I fixed the code, but instead of hiding do you not want to hide all then show the selected?

$(".btn").click(function() {
  var tabname = $(this).parent().attr("id")
  console.log(tabname)

  $(".tab").filter(function(index, elem) {
    return $(elem).attr("value") === '#'   tabname
  }).hide()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="tab01">
  <button > tab 1</button>
</div>
<div id="tab02">
  <button > tab 2</button>
</div>
<div id="tab03">
  <button > tab 3</button>
</div>

<div >
  <button  value="#tab01">This is tab content 1</button>
  <button  value="#tab02">This is tab content 2</button>
  <button  value="#tab03">This is tab content 3</button>
</div>

CodePudding user response:

Here is a solution with a CSS-selector instead of a filter:

$(".btn").click(function() {
 let sel='.tab[value="#' this.closest("div").id '"]';
 // console.log(sel)
 $(sel).hide()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="tab01">
  <button > button</button>
</div>
<div id="tab02">
  <button > button</button>
</div>
<div id="tab03">
  <button > button</button>
</div>

<div >
  <button  value="#tab01">This is button 1</button>
  <button  value="#tab02">This is button 2</button>
  <button  value="#tab03">This is button 3</button>
</div>

  • Related