Populate a select dropdown list with jQuery

Filed in Code 5 comments

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.

<form>
  <select name="dep">
    <option>Department</option>
    <option>Sales</option>
    <option>Support</option>
  </select>
  <select name="cname">
    <option>Contact name</option>
  </select>
</form>

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.

$(document).ready(function() {

// code here

});

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:

$(document).ready(function() {

$department = $("select[name='dep']");
$cname = $("select[name='cname']");

});

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.

$(document).ready(function() {
$department = $("select[name='dep']");
$cname = $("select[name='cname']");

$department.change(function() {

// code here

});
});

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.

$(document).ready(function() {
$department = $("select[name='dep']");
$cname = $("select[name='cname']");

$department.change(function() {

//if the value from department selection is ‘Sales’ then…
if ($(this).val() == "Sales") {
$("select[name='cname'] option").remove(); //remove all options from Contact names
$("<option>John Smith</option>").appendTo($cname); //add an option to Contact names
$("<option>Marry Jones</option>").appendTo($cname); //add an option to Contact names
}

});
});

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.

Final code:

$(document).ready(function() {
$department = $("select[name='dep']");
$cname = $("select[name='cname']");

$department.change(function() {

if ($(this).val() == "Sales") {
$("select[name='cname'] option").remove();
$("<option>John Smith</option>").appendTo($cname);
$("<option>Marry Jones</option>").appendTo($cname);
}

if ($(this).val() == "Support")
{
$("select[name='cname'] option").remove();
$("<option>Jessy McBeth</option>").appendTo($cname);
$("<option>Bob Smith</option>").appendTo($cname);
}

if ($(this).val() == "Department")
{
$("select[name='cname'] option").remove();
$("<option>Contact name</option>").appendTo($cname);
}

});
});

Once you understand the logic, the code won’t look as hard.

Still have questions? post them in the comments below!

Posted by Catalin   @   3 May 2011 5 comments
Tags : ,

Share This Post

RSS Digg Twitter StumbleUpon Delicious Technorati

5 Comments

Comments
Jan 20, 2012
5:21 AM
#1 azmi :

good tutorial. my problem solved.

could you show me example using database. i would like to play with dynamic data

May 12, 2012
1:27 PM
#2 Aneeq :

This is an easy to use code to select records from MySQL database table and display in dropdown combo box using PHP.

$cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());
$sql = “SELECT field_name FROM table_name”;
$rs = mysql_query($sql) or die(mysql_error());
echo “”;
while($row = mysql_fetch_array($rs)){
echo “”.$row["field_name"].”";
}mysql_free_result($rs);
echo “”;

Source:
http://phphelp.co/2012/05/10/how-to-fill-

a-dropdown-combo-box-in-php-from-mysql-database-table/

OR

http://addr.pk/a8cf

Jun 5, 2012
11:51 PM
#3 Naveen :

Thanks for breaking this down to so well.
I was able to understand this and implement it. However, i am trying to do the same by populating the 2 dropdown boxes from MySQL DB.
Typically I would embed the PHP code in the HTML to fetch row data and display it. Can i do the same inside the javascript ? Whats the best possible approach to solve my problem?

Jun 21, 2012
9:53 PM

thanks simple and clear.

Nov 17, 2012
4:17 AM
#5 Srinivas :

Thanks for the simple code.

Leave a Comment

Previous Post
«
Next Post
»
Luix designed by Video Game Music In conjunction with VPS Hosting , Website Hosting and Shared Hosting.