Today, I would like to share a quick and easy solution to link 2 list boxes with jQuery and AJAX.
Situation: we have two list boxes. One (number) is already populated. The second (letter) is populated according to what is selected on the first list box, via AJAX (not reloading the page).
We need to build two ASP pages.
Let's start and have fun!
The main page
The main page will have the relevant jQuery code and the HTML.
We will use jQuery and specifically its AJAX API. We first link to the library and then create a function triggered by a change in the first list box:
The above snippet should be place in the head of your main page. What is the function doing? It is fetching data (in the form of HTML tags) from another page (which we will create afterwards and which we will call "source.asp"). In order to retrieve the information we need, we are passing a parameter (ID). This parameter is taken from the first list box and appended to the url (so that our request will be "source.asp?id=1" for example).
var dataString = '?id='+ id;
I believe that the code is simple enough. No strange or magic things there.
In the body of the page we insert the two list boxes. As said, one is already populated. The second is empty.
When something changes in the "number" list box, the jQuery function is triggered and the second list box is populated. As said that is done via AJAX, calling the "source.asp" page. So we need to build the "source.asp" page.
<select name="number" class="number">
<select name="letter" class="letter">
The source.asp pageThe second asp page is very simple. It fetches data from the database and create a simple list of <option> tags which will be inserted inside the second <select> in the main page. At the beginning of the page, we query the database:
As usual, the above is just an example, so please remember to insert your connection string (yourconnectionstring) and your letters table (lettersTable).
Set PopDP = Server.CreateObject("ADODB.Recordset")
PopDP.ActiveConnection = yourconnectionstring
PopDP.Source = "SELECT * FROM lettersTable WHERE id = " + Replace(Request.QueryString("id"), "'", "''") + ""
PopDP.CursorType = 0
PopDP.CursorLocation = 2
PopDP.LockType = 1
PopDP_numRows = 0
In the body of your page, we insert the <option> tags using the data from the above recordset:
Again, nothing special here. Finally, we close the connection:
<%While (NOT PopDP.EOF)%>
If (PopDP.CursorType > 0) Then
Save your page as "source.asp".
Set PopDP = Nothing
Now you're ready to test the example.
Some further considerationsThe first list box is not dynamically populated. If you want to do so, just fetch the data from your database.
In the example we use the ID field as filter. It is obvious that all the fields used in the example are just because I need to show you "something". Please be sure to use your field names, connection, table names etc.
Ok. I believe that's all. Simple, straight forward and effective.
As usual, please share your thoughts!