Home > Software design >  jquery text inside each function search bar
jquery text inside each function search bar

Time:08-26

It prints an empty string, supposed to print "Admin" and hide the elements that don't contains the searchBar text, keyUp is being triggeree, it just gives me an empty string when i console.log($(this).text()), searchBar is an input field to search things in a list

const searchBar = $(".users-layout .search input")
searchBar.on("keyup", () => {
  if (searchBar.val() != "") {
    $(".users-list-name").each(() => {
      if (!$(this).text().toLowerCase().includes(searchBar.val().toLowerCase())) {
        console.log($(this).text())
        $(this).hide()
      } else {
        console.log($(this).text())
        $(this).show()
      }
    })
  }
})
<div >
  <a href="#" > <i ></i></a>
  <div >
    <div >
      <span >Admin</span>
      <p>Test Message</p>
    </div>
  </div>
  <div ><i ></i></div>
</div>
<div >
  <a href="#" > <i ></i></a>
  <div >
    <div >
      <span >Admin</span>
      <p>Test Message</p>
    </div>
  </div>
  <div ><i ></i></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

CodePudding user response:

at the end i resolved like this

searchBar.on("keyup", ()=>{
  if (searchBar.val() != "") {
    $(".users-list-name").each((i, obj)=>{
      console.log($(obj))
      if (!$(obj).text().toLowerCase().includes(searchBar.val().toLowerCase())){
        $(obj).parent().parent().parent().hide()
      } else {
        $(obj).parent().parent().parent().show()
      }
    }
  )
} else {
  $(".users-list").show()
}
})

CodePudding user response:

this was refering to the window. I fixed it so it grabs the actual element: let elem = $(".users-list-name")[index]

const searchBar = $(".users-layout .search input")
searchBar.on("keyup", () => {
  if (searchBar.val() != "") {
    $(".users-list-name").each(index => {
    let elem = $(".users-list-name")[index]
      if (!$(elem).text().toLowerCase().includes(searchBar.val().toLowerCase())) {
        console.log($(elem).text())
        $(elem).hide()
      } else {
        console.log($(elem).text())
        $(elem).show()
      }
    })
  }
})
<div >
  <div >
    <input />
  </div>
</div>

<div >
  <a href="#" > <i ></i></a>
  <div >
    <div >
      <span >Admin</span>
      <p>Test Message</p>
    </div>
  </div>
  <div ><i ></i></div>
</div>
<div >
  <a href="#" > <i ></i></a>
  <div >
    <div >
      <span >Admin</span>
      <p>Test Message</p>
    </div>
  </div>
  <div ><i ></i></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related