Jump to content
nomarie

Filter multiple lists

Recommended Posts

I'm basically trying to replicate https://www.w3schools.com/howto/howto_js_filter_lists.asp but with multiple ULs rather than a single one. I've had no problem with the HTML/CSS adaptations, but am stuck on the JS. Can anyone help?

Share this post


Link to post
Share on other sites

Like with the other Javascript examples, they typically use IDs for everything.  Since IDs need to be unique, you need a different way to access the elements in Javascript.  One option would be to pass the IDs of the text field and the UL list to the function instead of hard-coding  that in the function.  

Share this post


Link to post
Share on other sites

You probably only need to pass the relevant IDs to the function.

function myFunction(inputID, ulID) {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById(inputID);
  filter = input.value.toUpperCase();
  ul = document.getElementById(ulID);

 

Share this post


Link to post
Share on other sites

I've got two ULs with IDs 'ul1' and 'ul2'.

JS:

function journalsearch() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById('ul1','ul2');
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li.getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li.style.display = "";
    } else {
      li.style.display = "none";
    }
  }
}

Search box:

<input type="text" id="input1" onkeyup="journalsearch('ul1','ul2')" placeholder="Search for titles...">

Search filters the first list as expected, but nothing happens to the second.

Share this post


Link to post
Share on other sites

document.getElementById only returns one element, trying to pass more than one value to it has no effect.  Notice what I did in the post above, I replaced the IDs in the function with variables.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...