Fill select box dynamically using jquery

hello ,

you may noticed in so many website while filling registration form that depend on which state you select , the next select box (city) automatically filled with city name.

This thing achieved by jquery.  let’s create it.

HTML CODE

<select id="state" name="state" onchange="getCity(this.value)">
<option>Gujarat</option>
<option>Karnataka</option>
</select>
City
<select  id="city" name="city" >
<option>Select</option>
</select>

oky now write this jquery function


function getCity(s)
{
var url="getCity.php?s="+s;
$.ajax({
url: url,
method: "post",
success: function(response){
document.getElementById("city").innerHTML = response;

}

});
}

now, create getCity.php file and write bellow code inside that. (first create voluntaryregistration table inside phpmyadmin and write connection code on top of this file)


include "inc/connect.php";
$s = $_GET['s'];
$qry = "select city from voluntaryregistration where state = '$s'";
$res = mysql_query($qry) or die(mysql_error());
while($data = mysql_fetch_row($res))
{
echo "<option value=".$data[0].">" .$data[0]. "</option>"; 

}

NOTE:

  • write jquery function inside <head> <script > … </script> </head> tag.
  • download jquery from http://code.jquery.com/jquery-1.8.3.min.js
  • add jquery file by <script src=”jquery-1.8.3.min.js > </script> on top of jquery function.

Problem:

if you have city name like “surendra nagar” then only surendra will stored in side option value ,
like <option value=”surendra” nagar> surendra nagar </option>

so if you are fetching this record by _POST or _GET variable you will get only surendra.

Solution

use this code inside php script.

while($data = mysql_fetch_row($res))
{
?>
<option value = “<?php echo $data[0]; ?>” ><?php echo $data[0]; ?></option>
<?php
}
?>

oky done!!

hope you like it!!

Advertisements

3 thoughts on “Fill select box dynamically using jquery

  1. My brother suggested I might like this website. He was entirely right.
    This post truly made my day. You cann’t imagine just how much time I had spent for this info! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s