Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.
Related
I want to add part search into a website powered by WordPress. I have currently achieved the function, but I have trouble of integrating it into WordPress. I tried several ways but the dynamic dependent select box still not working.
I followed this tutorial: Dynamic Dependent Select Box using jQuery, Ajax and PHP
Below are my code which works well outside WordPress.
index.php
<head>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/ajax-ps.js"></script>
</head>
<body>
<form class="select-boxes" action="ps-result.php" method="POST">
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" class="col-md-2 col-sm-2 col-xs-10" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" class="col-md-2 col-sm-2 col-xs-10" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" class="col-md-2 col-sm-2 col-xs-10" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" class="col-md-2 col-sm-2 col-xs-10" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" class="col-md-2 col-sm-2 col-xs-10" value="Search">
</form>
</body>
ajax-ps.js
$(document).ready(function(){
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'manufact_id='+manufactID,
success:function(type_data){
$('#type').html(type_data);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'type_id='+typeID,
success:function(year_data){
$('#year').html(year_data);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'year_id='+yearID,
success:function(model_data){
$('#model').html(model_data);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
ajax-data.php
include('dbConfig.php');
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
Now the problem is, when select the first box, the second one becomes empty, nothing is returned from the database:
Capture - After select the first box
Really appreicate Christos Lytras to help me solve the previous problem.
I have a new problem with action="ps-result.php" in the line <form class="select-boxes" action="ps-result.php" method="POST">.
ps-result.php
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
}
else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
...
</div>
<?php get_footer(); ?>
Now when I click Search, it returns
Fatal error: Call to undefined function get_header() in /Applications/MAMP/htdocs/wordpress/wp-content/themes/myTheme/inc/ps-result.php on line 42.
The proper way to do this, is to create a wordpress shortcode and then use that shortcode wherever you want, page or post, but if you want to create something more specific, then you should create a small wordpress plugin. I won't get into this, but it’s really not a big deal to create a simple wordpress plugin having such functionality. I’ll go through the steps on how you can have this working in wordpress with the files and the code you already have.
I assume you already have the tables of your example created. My tables are like this:
wp_citytours_dynsel_cities
wp_citytours_dynsel_states
wp_citytours_dynsel_countries
I have imported some data and I have all those tables filled with proper data. I can provide some sql files if you like, but I assume you already have your tables filled with the proper data for each table.
My test theme root directory is:
/wp-content/themes/citytours/
I have created the directory under my theme root directory and I have included all the code files there, so we have 3 files:
/wp-content/themes/citytours/dynsel/index-partial.php
<?php
//Include database configuration file
include('dbConfig.php');
//Get all country data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<script type="text/javascript">
jQuery(function($) {
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
/wp-content/themes/citytours/dynsel/dbConfig.php
<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'xxxx';
$dbPassword = 'xxxx';
$dbName = 'xxxx';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
/wp-content/themes/citytours/dynsel/ajaxData.php
<?php
//Include database configuration file
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
As you can see, the index-partial.php now contains only needed code, without <body>, <head> and script files included. Wordpress already includes jQuery to the application for most themes, but you should always check that.
Now, you can add the functionality wherever you want, even at the theme index.php file, but always with caution. I have used theme's single post template file, which is single-post.php. I have included the example code, under the main post body inside a div. I just include the index-partial.php like this:
<div class="<?php echo esc_attr( $content_class ); ?>">
<div class="box_style_1">
...
</div><!-- end box_style_1 -->
<div class="box_style_1">
<?php include(__DIR__.'/dynsel/index-partial.php'); ?>
</div>
</div><!-- End col-md-9-->
I also have used the wordpress home_url function, to have a proper url rooted for the ajaxData.php file like this:
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>'
Now, if you have followed all these steps, then you should have your code example working at under each post. You can now included it wherever you want by using that line of code <?php include(__DIR__.'/dynsel/index-partial.php'); ?>.
Please let me know if that worked for you.
I have this select , i wanna save each value after change , save it and use in other select
This is my code :
<?
$sql = "SELECT * FROM championnat ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="nom_championnat" id="nom_championnat" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option value=" <?php echo $r['idChampionnat']?>" name="nom_championnat" selected >
<?php echo $r['nomChampionnat'] ?></option>
<?php
}
}
}
?>
</select>
</div>
I need the variable $r['idChampionnat'] to save it in each select and use it in this requete , how can it asve and put it in that requete sql ????
<?php
$sql = "SELECT * FROM equipe where idChampionnat=???? ";
$result = $conn->query(sprintf($sql));
if($result){
if ($result->num_rows != 0)
{
$rows=array();
?>
<select name="equipe1" >
<option value=""></option>
<?php
while($r=mysqli_fetch_assoc($result))
{
?>
<option required value=" <?php echo $r['nomEquipe']?>" name="equipe1" selected ><?php echo $r['nomEquipe'] ?>
</option>
<?php
}
}
}
?>
</select>
just to clear it ,
You need to use jQuery to fire an AJAX call when the first box is selected.
Its been a while since I've done this but this should give you some idea. I took some code from here and here as example
Say your html looks like this
<select id="nom_championnat">
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select id="equipe1"></select>
then you need to tell jquery what to do when nom_championnat changes selection
$('#nom_championnat').change(function() {
var data = "";
$.ajax({
type:"POST",
url : "queryfile.php",
data : "value="+$(this).val(),
async: false,
success : function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var string = data.message.split(",");
var array = string.filter(function(e){return e;});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
and then you need a queryfile.php to handle the ajax requests, something like
<?php
print_r($_POST);
$value = $_POST["value"];
$sql = "select where {$value} ..."
$result = execute($sql);
echo $result;
?>
Today, I went to code a form with Dynamic dropwdown list in it.
Mission : I want to make dynamic dropdown list when User choose Category, then the store with that category will appear.
It is the form :
<select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
<option value="-1"> - Choose Category -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select>
<label for="inputName" class="control-label">Store Name</label>
<select name="store" class="form-control" id="store">
<option value="-1"> - Choose Store -</option>
</select>
This is the AJAX :
<!-- linking drop down AJAX -->
<script type="text/javascript">
var ajaxku=buatajax();
function ajaxStore(id){
var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
ajaxku.onreadystatechange=stateChanged;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function buatajax(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function stateChanged(){
var data;
if (ajaxku.readyState==4){
data=ajaxku.responseText;
if(data.length>=0){
document.getElementById("store").innerHTML = data
}else{
document.getElementById("store").value = "<option selected>- Choose Store -</option>";
}
}
}
</script>
And this the code of StoreAPIService.php :
session_start();
$stores = array();
$store_category_id = $_GET['category'];
try
{
//$client = new GuzzleClient();
$response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
echo"<option value=''>- Choose Store -</option>";
foreach ($error['stores'] as $store)
{
$mainStore = new StoreSummary();
echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
array_push($stores, $mainStore);
}
}
}
I got no error, but the Store with 'Category' that I Choose is not appearing.
Could anyone please check if I went wrong.
thanks for your helps.
You were trying to change options of a dropdown menu. i did this by changing dropdown menu itself.
I created a div with id="store" in the html form and changing the innerHTML of div using ajax
html form
<select name="category" class="form-control" id="category" onchange="ajaxStore(this.value)">
<option value="-1"> - Choose Category -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select><label for="inputName" class="control-label">Store Name</label>
<div id="store"><select name="store" class="form-control">
<option value="-1"> - Choose Store -</option>
</select>
</div> <!--end of store -->
ajax code
<!-- linking drop down AJAX -->
<script type="text/javascript">
var ajaxku=buatajax();
function ajaxStore(id){
var url="objects/StoreAPIService.php?category="+id+"&sid="+Math.random();
ajaxku.onreadystatechange=stateChanged;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function buatajax(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function stateChanged(){
var data;
if (ajaxku.readyState==4){
data=ajaxku.responseText;
if(data.length>=0){
document.getElementById("store").innerHTML = data
}else{
document.getElementById("store").value = "<select name=\"store\" class=\"form-control\">
<option value=\"-1\"> - Choose Store -</option>
</select>";
}
}
}
</script>
StoreAPIService.php :
session_start();
$stores = array();
$store_category_id = $_GET['category'];
try
{
//$client = new GuzzleClient();
$response = $this->client->get('admin/store/bycat/rev/'.$store_category_id,
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);
$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
echo "<select name=\"store\" class=\"form-control\">
<option value=\"\">- Choose Store -</option>";
foreach ($error['stores'] as $store)
{
$mainStore = new StoreSummary();
echo "<option value='{$mainStore->setStoreId($store['store_id'])};'>{$mainStore->setStoreName($store['store_name'])};</option>";
array_push($stores, $mainStore);
}//end of foreach
echo "</select>"
}
}
I am using dropdown to select values, and after I click the submit button, my values change. Please help me retain the selected values. Using POST method I have got the solution, but I want to use with GET method. Is it possible?
1.) 1st select stmt:
<form action="" method="GET">
<select name="sort" >
<option value="inc_patientName">Patient Name</option>
<option value="inc_date">Date</option>
<option value="inc_status">Status</option>
<option value="inc_patientAge">Age</option>
</select>
<input type="submit" name="GETREPORT" value="Get Report"/>
if ($_GET)
{echo"hi";}
</form>
2.) 2nd select with while
<?php
//Selecting ward from table ward master
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
echo "<select name='ward'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['ward_id'] . "'>" . $row['ward_name'] . "</option>";
}
echo "</select>";
?>
3.) 3rd select with javascript:
<select name="daydropdown" id="daydropdown" ></select>
<select name="monthdropdown" id="monthdropdown"></select>
<select name="yeardropdown" id="yeardropdown"></select>
<script type="text/javascript">
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
Javascript code:
<script type="text/javascript">
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield)
{
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=1; i<=31; i++)
dayfield.options[i]=new Option(i, i)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1999
for (var y=0; y<45; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
try
if(isset($_GET['sort'])) {
echo $_GET['sort'];
}
and get selected index
<option value="inc_patientName" <?php if (isset($_GET['sort']) && $_GET['sort'] == "inc_patientName") echo 'selected="seleceted"'; ?>>Patient Name</option>
and so on for all options values match
For 2nd dropdown:-
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['ward_id'];?>" <?php if (isset($_GET['sort']) && $_GET['sort'] == $row['ward_id']) echo 'selected="seleceted"'; ?>><?php echo $row['ward_name'];?></option>
<?php }
use it like this... it myt work.
<select name="ward">
<?php
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
if ($_GET['ward']==$row["ward_id"]) {
echo '<option selected="selected" value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
} else {
echo '<option value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
}
}
?>
</select>
You can do something like this:
<select name="sort" >
<option value="inc_patientName"<?php if ($_GET['sort'] == 'inc_patientName') echo ' selected="seleceted"'; ?>>Patient Name</option>
<option value="inc_date"<?php if ($_GET['sort'] == 'inc_date') echo ' selected="seleceted"'; ?>>Date</option>
<option value="inc_status" <?php if ($_GET['sort'] == 'inc_status') echo ' selected="seleceted"'; ?>>Status</option>
<option value="inc_patientAge"<?php if ($_GET['sort'] == 'inc_patientAge') echo ' selected="seleceted"'; ?>>Age</option>
</select>
Try this:
Use this function in ur script:
function setday(id,elementname)
{
document.getElementById(elementname).value=id;
}
Use this in ur php form, Repeat the same code for year and month dropdowns:
if (isset($_GET['daydropdown']))
{
echo "<script type='text/javascript'>setday('".$_GET['daydropdown']."','daydropdown')</script>";
}
I have five dropdown list which depending on the selection the display changes to block.
The problem comes when values are posted back. The drop down list does not show the values. This likely because of javascript that by default displays as none the drop down list. The javascript listens for onclick. Here is part of the javascripts:
function changeOptions() {
var form = window.document.getElementById("frm1");
var sv = window.document.getElementById("sv");
var sv2= window.document.getElementById("sv2");
var sv3 = window.document.getElementById("sv3");
var sv4= window.document.getElementById("sv4");
var sv5 = window.document.getElementById("sv5");
if (form.radioButton1.checked) {
sv2.style.display = "none";
sv3.style.display = "none";
sv4.style.display = "none";
sv5.style.display = "none";
sv.style.display = "block";
//sv.selectedIndex =0;
else if (form.radioButton5.checked) {
sv.style.display = "none";
sv2.style.display = "none";
sv3.style.display = "none";
sv4.style.display = "none";
sv5.style.display = "block";
sv5.selectedIndex = 0;
}
}
window.document.getElementById("radioButton5").onclick = changeOptions;
The dropdown menu is populated from my database. Below is the code. There are five of them The display:none changes to block depending which radio button is clicked.
<select style="width:200px; **display:none**" name="pGroup" id="sv" >
<option value="Choose an Option" >Choose Product Group</option>
<?php
$selGroup = isset($_GET['pGroup'])?$_GET['pGroup']:"";
$sql="SELECT DISTINCT pGroup FROM cr39 WHERE ";
$sql.="HeadingNo = 3 ORDER BY pGroup ASC";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<option <?php if($data['pGroup'] == $selGroup) echo 'selected="selected"'; ?> value ="<?php echo $data['pGroup'] ?>" ><?php echo $data['pGroup'] ?></option>
<?php } ?>
</select>
.
.
.
.
<select style="width:200px; **display:none**" name="pGroup5" id="sv5">
<option value="Choose an Option" >Choose Product Group</option>
<?php
$selGroup = isset($_GET['pGroup5'])?$_GET['pGroup5']:"";
$sql="SELECT DISTINCT pGroup FROM cr39 WHERE ";
$sql.="HeadingNo = 7 ORDER BY pGroup ASC";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<option <?php if($data['pGroup'] == $selGroup) echo 'selected="selected"'; ?> value ="<?php echo $data['pGroup'] ?>" ><?php echo $data['pGroup'] ?></option>
<?php } ?>
</select>
I am a novice in this and would like help on how to retain the value on my dropdownon postback.
per comment above, would need to see more code to be exact, but here is a pseudo version that you may be able to adapt;
<body
<?PHP if(isset($_GET['selectedGroupId'];)){ ?>
onload='window.document.getElementById("radioButton<?PHP echo $_GET['selectedGroupId']; ?>").click()'
<?PHP } ?>
>
replace $_GET['selectedGroupId'] with your fieldname/id
see if that gets you on the right track