It’s common to meet situations where you want a dropdown list to be updated depending on a visitor’s input.
Let’s say we have a contact form and we want to list contact names according to the department the visitor selects. Namely, in our case, we’ll have different contact names for the ‘sales’ and ‘support’ departments.
Both select fields have a ‘name’ attribute, so we can find and select them with jQuery. The logic of the functions we’ll build is pretty simple:
IF the ‘Sales’ option is selected, then add ‘some names’ to the second select input, and the same goes for the other departments.
So let’s get right on it!
We’ll build all of our code inside a jQuery ready function so the code will only be run after the entire HTML elements (the DOM) have finished loading.
To avoid making jQuery go through the DOM over and over again when we’ll fetch our select inputs, we’ll add the selects to variables:
From now on, whether we’ll use $(“select[name='dep']“) or $department, it will mean the same thing, difference is though, jQuery will no longer traverse the document again with $department, it will just know where that element is. This is very important for larger scripts that may slow down a web page.
Now that we’ve added our select inputs to variables, we’ll use jQuery’s onChange function to detect when our department current selection changes.
We have our onChange function, now it’s just a matter of a few if-and-else conditions to know when a certain department is selected, so let’s start with the ‘Sales’ department.
I believe the code is pretty self-explanatory, we’ve checked if the selected option from ‘department’ is ‘Sales’ and removed all options from the second selection and added two new names. The very same if-and-else condition will go for the rest of the departments.
Once you understand the logic, the code won’t look as hard.
Still have questions? post them in the comments below!