Solved

Filter listbox

Posted on 2006-11-01
15
784 Views
Last Modified: 2007-11-27
I have two list boxes list1 and list2 . If I select one item  from list1 can I filter the 2nd  listbox  based on the one I selected in the first one using  javascript ?
Can you please give some sample code ?

I am using asp.net.I am trying to avoid a post back .
Since I populated  all the data for list1 and list2, I just wan t filter the 2nd one based on the selection made In the list1
Thanks
0
Comment
Question by:aio419
  • 8
  • 4
  • 2
  • +1
15 Comments
 
LVL 19

Expert Comment

by:nschafer
Comment Utility
Hi aio419,

How is the data in the list boxes related?
Do the values of the options in ListBox1 relate to the displayed text or value of ListBox2?
If not, then we will likely have to set an array for the relationship.

Since you stated that both list boxes are already populated, I assume that you don't want to change things so that listBox2 is not populated until a selection is made in ListBox1.

Neal.
0
 
LVL 41

Expert Comment

by:HonorGod
Comment Utility
The short answer is yes.  However, it depends upon what you mean when you say "filter".
Here is a framework.  What kind of filtering do you have in mind?
-------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> List Filter </title>
<script type='text/javascript'>
  function filter( id1, id2 ) {
    if ( document.getElementById ) {
      var L1 = document.getElementById( id1 );
      var L2 = document.getElementById( id2 );
      var I1 = L1.selectedIndex;
      var opts = L1.getElementsByTagName( 'option' );
      alert( 'You picked: ' + opts[ I1 ].value );
    }
  }
</script>  
</head>
<body>
<table border='1'>
  <tr>
    <td>
      <select id='list1' onchange='filter("list1","list2")'>
        <option>Pick something</option>
        <option>One</option>
        <option>Two</option>
        <option>Three</option>
      </select>
    </td>
    <td>
      <select id='list2' onchange='filter("list2","list1")'>
        <option>Pick something</option>
        <option>Uno</option>
        <option>Dos</option>
        <option>Tres</option>
      </select>
    </td>
  </tr>
</table>
</body>
</html>
0
 
LVL 28

Expert Comment

by:Pravin Asar
Comment Utility
Here I have two example in one code...
1. Dynamically updating the options value
2. Use of optgroup

Since the you could use what suits you best..

Have questions, ask me.


<html>
<body>
<script language="javascript">
function updateSelMenu2 (srcObj, trgObj) {

    // Clean the options from trgObj (sel2)
    if (trgObj.options) { trgObj.options.length= 0;}

    // User not selected valid option (see the code for sel1)
    if (srcObj.value < 0) { return false; }

    // Options for trgObj (sel2)

    var trgStr = srcObj.value;

    // Split the commas delimited string into pieces
    var ts = trgStr.split (',');

    // Loop over to create and assign option elements to trgObj  (sel2)
    for (ix=0; ix < ts.length; ix++) {
         trgObj.options[ix] = new Option (ts[ix], ts[ix]);
    }
    // Set the length for trgObj options
    trgObj.options.length = ts.length;
}
</script>
<form name="form1">
<select name="sel1" onchange="updateSelMenu2(this, this.form.sel2);">
      <option value="poodle,puli,greyhound" selected>Dogs</option>
      <option value="trout,mackerel,basse" >Fish</option>
      <option value="robin,hummingbird,crow">Birds</option>
</select>
<select name="sel2">
</select>
</form>
<script language="javascript">
updateSelMenu2(document.form1.sel1, document.form1.sel2);
</script>

<form name="form2">
<select name="sel">
      <optgroup id="dogs" label="DOGS">
            <option value="poodle">poodle</option>
            <option value="puli" >puli</option>
            <option value="greyhound">greyfound</option>
      </optgroup>
      <optgroup id="fish" label="FISH">
            <option value="trout">trout</option>
            <option value="mackerel" >mackerel</option>
            <option value="bass">bass</option>
      </optgroup>
      <optgroup id="birds" label="BIRDS">
            <option value="robin">robin</option>
            <option value="hummingbird" >hummingbird</option>
            <option value="crow">crow</option>
      </optgroup>
</select>
</form>
</body>
</html>
0
 

Author Comment

by:aio419
Comment Utility
The sample data is
List1
                LCO           Company
      00      PRODUCTS LIABILITY PROGRAMS  
      01      PRODUCTS LIABILITY PROGRAMS  
      03      Naga                          
      00      MARKETING CENTER    
      01      MARKETING CENTER                  

When I select  Naga in list 1, list 2 should show only  Naga and Saga ( LCO=03)
(from  08,03 and  09,03  get 2nd part after the comma which is 03 )

List 2  data is like this

MCOLCO   Company
08,00      PRODUCTS LIABILITY PROGRAMS  
08,01      PRODUCTS LIABILITY PROGRAMS  
08,03      Naga                          
04,00      MARKETING CENTER    
04,01      MARKETING CENTER  
09,03        Saga    

Where MOCLCO  is   MCO + LCO separated by a comma.
Sorry for the confusion.
0
 

Author Comment

by:aio419
Comment Utility
Any help would be appreciated.
0
 

Author Comment

by:aio419
Comment Utility
If you want me to increase the points,please let me know.
Please help...
0
 
LVL 41

Expert Comment

by:HonorGod
Comment Utility
OK, given that information, we still have a problem

When an entry is selected in List 1, do we use the  LCO & Company to "remove" matching entries from List 2?
Is the uniqueness identified by LCO + Company.  We can see that LCO is not unique.  But we do see that LCO + Company appears to be unique given this sample information.

Is this what you want?
---------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> List Filter </title>
<script type='text/javascript'>
  function filter( id1, id2 ) {
    if ( document.getElementById ) {
      var L1 = document.getElementById( id1 );
      var L2 = document.getElementById( id2 );
      var I1 = L1.selectedIndex;
      var opts = L1.getElementsByTagName( 'option' );
      var picked = opts[ I1 ].value;
      var opts = L2.getElementsByTagName( 'option' );
      for ( var i = opts.length - 1; i > 0; --i ) {
        var val = opts[ i ].value;
        if ( val.indexOf( picked ) > -1 ) {
          opts[ i ].parentNode.removeChild( opts[ i ] );
        }
      }
    }
  }
</script>  
</head>
<body>
<table border='1'>
  <tr>
    <td>
      <select id='list1' onchange='filter("list1","list2")'>
        <option>00 PRODUCTS LIABILITY PROGRAMS</option>
        <option>01 PRODUCTS LIABILITY PROGRAMS</option>
        <option>03 Naga</option>
        <option>00 MARKETING CENTER</option>
        <option>01 MARKETING CENTER</option>
      </select>
    </td>
    <td>
      <select id='list2' onchange='filter("list2","list1")'>
        <option>08,00 PRODUCTS LIABILITY PROGRAMS</option>
        <option>08,01 PRODUCTS LIABILITY PROGRAMS</option>
        <option>08,03 Naga</option>
        <option>04,00 MARKETING CENTER</option>
        <option>04,01 MARKETING CENTER</option>
        <option>09,03 Saga</option>
      </select>
    </td>
  </tr>
</table>
</body>
</html>
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 19

Accepted Solution

by:
nschafer earned 60 total points
Comment Utility
My original question remains.  How do the list boxes link.  Are the items in the left the values of the options?  If so then this shouldn't be too difficult.  We start by creating a copy of List2 so that we don't lose the options that are filtered out of the list.  We can do this easily using the cloneNode method.  We then modify the newly created node to make it hidden and give it a unique ID before adding it to the document.  This Copy is only made once when the document is loaded.

Now that we have a backup copy of all the options for List2 we can filter List2 by removing all of the elements from it and then just adding in those that are appropriate.

Here's an example that does just that.

Neal.
--------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>List Box Filtering</title>
    <script>
    // make a hidden copy of list 2 with the id "List2Copy"
    function makeCopy() {
      var l2 = document.getElementById("List2");
      var l2c = l2.cloneNode(true); // make a copy of List2
      l2c.id = "List2Copy"; // give the new node a unique name.
      l2c.disabled = true;  // disable so it won't pass with form.
      l2c.style.display = "none";  // make the new node hidden
      document.body.appendChild(l2c);  // add the new node to the body
    }
    function filter(val) {
      var l2 = document.getElementById("List2");
      var l2c = document.getElementById("List2Copy");
      l2.options.length = 0;  // empty List2
      // add the Choose one option
      opt = l2c.options[0].cloneNode(true);
      l2.appendChild(opt);
      for (i=1;i<l2c.length;i++) { // loop through options in copy of List2
        var copyVal = l2c.options[i].value.split(",")[1]; // get the value from the copied List
        if ( copyVal == val ) {  // check for match
          opt = l2c.options[i].cloneNode(true);  // copy the correct option
          l2.appendChild(opt)  // add it into List2
        }
      }
    }
    </script>
</head>
<body onload="makeCopy();">
<form name="form1" method="Post" action="" >
<select id="List1" name="List1" onchange="filter(this.value);">
<option value="-1">Choose One</option>
<option value="00">Products Liability Programs</option>
<option value="01">Products Liability Programs</option>
<option value="03">Naga</option>
<option value="00">Marketing Center</option>
<option value="01">Marketing Center</option>
</select>
<select id="List2" name="List2" onchange="alert(this.value);">
<option value="-1">Choose One</option>
<option value="08,00">Products Liability Program</option>
<option value="08,01">Products Liability Program</option>
<option value="08,03">Naga</option>
<option value="04,00">Marketing Center</option>
<option value="04,01">Marketing Center</option>
<option value="09,03">Saga</option>
</select>
</form>
</body>
</html>




0
 

Author Comment

by:aio419
Comment Utility
Thanks for the replu guys. here are the answer to the question you asked.
 How do the list boxes link. From a database query
  Are the items in the left the values of the options? yes

in this case 1st list is from a LOC table and the 2nd one like this
SELECT Distinct MCOLOC= MCO+','+ loc,MasterCompany FROM viewMCO.
In this case which answer can i use,Please advice.I am not  very good in javascript.
Thanks
0
 

Author Comment

by:aio419
Comment Utility
One more thing.First they need to pick an itemfromlist1, then only list 2 will show the filtered items corresponding to list1's value selected.
Thanks
0
 

Author Comment

by:aio419
Comment Utility
Please wait .Looks like nschafer's reply with ALL THE COMMENTS WILL help me.
0
 

Author Comment

by:aio419
Comment Utility
Thanks Guys for the reply.

nschafer,
That is great! awesome  work..
One question about the code.
Why you did not declare  ‘opt’ using var  and did not make any error?
opt = l2c.options[0].cloneNode(true);

And how do you debug javascript  if there is any error or say you want to see the values in opt? (other than clicking on the yellow error at the bottomleft of the browser)
Is there any way to do that.  
0
 
LVL 19

Expert Comment

by:nschafer
Comment Utility
A couple of points here

1. The var declaration is not required by javascript which is why it did not cause an error when I neglected to use it.  I try to use it the first time I declare a variable as a good programming practice.  Sometimes I forget.

2. I would recommend using Firefox instead of IE when working with javascript at least for troubleshooting.  There are several extensions to firefox to make debuggin javascript relatively painless.  On the other hand, you still need to test in IE and other browsers as javascript does not work the same in all browsers.  

3. I generally use the alert() function of javascript to output data as I'm working on a script.  This way I can see what the values are and ensure that I have parsed strings correctly or things like that.  

Neal.
0
 

Author Comment

by:aio419
Comment Utility
Neal, that is great. Your explanation and answers are awesome. You are a great EXPERT.
Thanks a lot  for the help.

(I increased the points by 50%)
0
 
LVL 19

Expert Comment

by:nschafer
Comment Utility
You are welcome.  I'm glad I could help.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

5 Experts available now in Live!

Get 1:1 Help Now