default setting for option select - php

I have been trying for weeks to solve this problem and as a last resort I seek help here.
I am using option tag to display 4 options. When I select an option it loads a .php file. The code I have is not too elegant but it does work.
<select name="history" class="button">
<option value="1" selected>Today</option>
<option value="2">Yesterday</option>
<option value="3">This Month</option>
<option value="4">This Year</option>
</select>
<div id="txtHint"><b></b></div>
<script>
$('[name="history"]').on('change', function() {
var ajaxMethod = "today.php";
switch($(this).val())
{
case "1":
ajaxMethod = "today.php";
break;
case "2":
ajaxMethod = "yesterday.php";
break;
case "3":
ajaxMethod = "monthly.php";
break;
case "4":
ajaxMethod = "yearly.php";
break;
}
$("#txtHint b").load(ajaxMethod);
});
</script>
All the .php files have the same table but make different mysql queries.
When I refresh the page, it clears the block and I have to select an option again. Is it possible to load an option as a default when the page loads? Otherwise I have an empty block before making a selection.
I tried having the table in the block and having each file only query the mysql but that does not work.
Any suggestions would be appreciated
For completeness I have included the today.php
<?php
$result = mysqli_query($con, "
SELECT max(Tmax), min(Tmin), max(R)
FROM alldata
WHERE DATE(DateTime) = CURDATE()
"
);
while ($row = mysqli_fetch_array($result)) {
$maxTemp = $row['max(Tmax)'];
$minTemp = $row['min(Tmin)'];
$totalRain = $row['max(R)'];
}
?>
<table id="historical">
<tr>
<td>
</td>
<td>
<?php echo 'Maximum'?>
</td>
<td>
<?php echo 'Minimum'?>
</td>
</tr>
<tr>
<td>
<img src="images/temp.png">
</td>
<td>
<?php echo $maxTemp." °C"?>
</td>
<td>
<?php echo $minTemp." °C"?>
</td>
</tr>
<tr>
<td>
<img src="images/rain.png">
</td>
<td>
<?php echo $totalRain." °C"?>
</td>
</tr>
</table>

To restore the selected option when you refresh the page.. TRY
1.Fetch data from DB to select the default option while loading the page. (If you store the option value in DB).
OR Use Sessions or cookie to store the selected data temporarly. And select the default option w.r to session or cookie data.

After a lot of testing, this is the code that fits the purpose.
It may help other users.
<select id="recordsSelector" class="button">
<option value="today" selected>
<?php echo "Today"?>
</option>
<option value="yesterday">
<?php echo "Yesterday"?>
</option>
<option value="thisMonth">
<?php echo "This Month"?>
</option>
<option value="thisYear">
<?php echo "This Year"?>
</option>
</select>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
stationData('<?php echo $defaultStats?>');
function stationData(period){
$(".records").html("");
if(period=="today"){
$("#almanacheading").html("Today");
}
if(period=="yesterday"){
$("#almanacheading").html("Yesterday");
}
if(period=="thisMonth"){
$("#almanacheading").html("This Month");
}
if(period=="thisYear"){
$("#almanacheading").html("This Year");
}
$.ajax({
url : "almanac.php?period="+period,
dataType : 'json',
success : function (json) {
$("#historyTMax").html(json['maxT']);
$("#historyTMin").html(json['minT']);
$("#historyHMax").html(json['maxH']);
$("#historyHMin").html(json['minH']);
$("#historyDMax").html(json['maxD']);
$("#historyDMin").html(json['minD']);
$("#historyPMax").html(json['maxP']);
$("#historyPMin").html(json['minP']);
},
});
}
$("#recordsSelector").change(function(){
period = $(this).val();
stationData(period);
});
$("#recordsSelector").val('<?php echo $defaultStats?>');
</script>

Related

Dynamic dropdown with auto select one option and it's sub-dropdown options

I have a dropdown in which one is for states and second one is it's sub category, which shows name of cities on basis of first dropdown.
Right now user need to select one category then subcategories load,
What change I want is "To set one value as default and load it's subcategories too" at load of page, and further user select different category so it should load it's subcategories accordingly.
Index.php:
<form name="insert" action="" method="post">
<table width="100%" height="117" border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%">
<select onChange="getdistrict(this.value);" name="state" id="state" class="form-control">
<option value="">Select</option>
<?php $query =
mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>">
<?php echo $row['StateName'];?>
</option>
<?php }?>
</select>
</td>
</tr><tr>
<th scope="row">District :</th>
<td>
<select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data: "state_id=" + val,
success: function (data) {
$("#district-list").html(data);
},
});
}
</script>
get_district.php:
<?php
require_once("config.php");
if(!empty($_POST["state_id"])){
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query)){
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>
You would need to do 2 things
1.) insert a selected flag into the input
2.) activate the second dropdown on page load
1.) If the selected entry does never change then hardcode the default selected field in your code like if $var = XXX then echo "selected".
If you have any function which calculates the default value e.g. a geolocation service like e.g. maxmind.com which takes the users remote IP address and outputs his current state, then use this result to set the selected entry.
<?php
while($row=mysqli_fetch_array($query)){
$row["StCode"] == "DESIRED_VALUE" ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> ><?php echo $row['StateName'];?>
</option>
[...]
Or add a field in the table SELECTED where you mark the default record with 1.
<?php
while($row=mysqli_fetch_array($query)){
$row["selected"] == 1 ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> >
<?php echo $row['StateName'];?>
</option>
[...]
2.) You have to set the second select dropdown on page load. There are several ways to do this - this is explained here in detail:
Jquery execute onchange event on onload

Updating a second dropdown after the first one has been chosen in javascript/php/html

I need an example that can let me populate the 2nd,3rd,...,7th dropdown list (all same entries) after the 1st dropdown list has been selected. I have all the values stored in an array in PHP before the HTML head.
I've looked at some examples, and couldnt find a specific solution
For example:
Let's say I have a warehouse full of franchisees and outlets under those aforementioned franchisees, I need to create order lists for 7 days ahead for that specific franchisee with n outlets. My solution was that the user/warehouse operator would pick a franchisee, then the 2nd (up to 7th) drop down list would have the outlets who are under that picked franchisee.
Thanks.
<?php
$productClass = new product();
$productClass->setProductList();
$franchiseeClass = new users();
$franchiseeClass->getAndSetAllFranchisees();
$franchiseeArray = $franchiseeClass->getUserList();
$operatorOutletClass = new users();
$operatorOutletClass->getAndSetUserByLevel("5");
?>
<html><head></head><body>
<div align="center">
<form name="BBOFranchisee" method="post" action="?" onSubmit="return checkSubmit()">
<table align="center" border="1">
<tr>
<td>
Franchisee:
</td>
<td colspan="8">
<select name="displayFranchisee" size="1" onChange="populateOutlet('findOutletByFranchisee.php?fid='+this.value)">
<option label="franchisees" value="0">--Choose Franchisee--</option>
<?php
for($i=0;$i<count($franchiseeArray);$i++)
{
foreach($franchiseeArray[$i] as $key => $val)
{
echo "<option label=\"franchisees\" value=\"$key\">$val</option>\n";
}
} ?>
</select>
</td>
</tr>
<tr>
<?php for($j=0;$j<7;$j++) { ?>
<td>
Outlet:
<select name="displayOutlet<?php echo $j; ?>" size="1">
<option label="outlets" value="0"> </option>
</select>
</td>
<?php } ?>
</tr>
</body>
</html>
I guess the continuation is the javascript part.. i tried to look at the solution that http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html provides, but it wont work with multiple drop downs.
In order to use that javascript example, you need to add an id to your 2nd-7th selects - id="displayOutlet<?php echo $j; ?>"
<?php for($j=0;$j<7;$j++) { ?>
<td>
Outlet:
<select name="displayOutlet<?php echo $j; ?>" id="displayOutlet<?php echo $j; ?>"size="1">
<option label="outlets" value="0"> </option>
</select>
</td>
<?php } ?>
Then in your javascript code, you can add a loop for the 2nd-7th selects.
if(req.status == 200) { // which represents ok status
for(var i=0;i<7;i++){
document.getElementById('displayOutlet'+i).innerHTML=req.responseText;
}
}

Remove select tag with text input if user select the certain option which cascade that

I want to make that if user is select certain option(provided from database) only one value then the other option tag appear to select else for all rest of other options user have text box to enter the value. Something like the below-
<tr>
<td><span class="alert">* </span>Country:</td>
<td><select name="country_id" class="medforminput" id="country_id" onchange="getState('select_state.php?country_id='+this.value)">
<option value="Select Country">Select Country</option>
<?php
while($row4=mysql_fetch_array($coun1))
{ ?>
<option value="<?php echo $row4['country_id']; ?>">
<?php echo $row4['country_name']; ?></option>
<?php }?>
<option value="others">Others</option>
</select></td>
</tr>
<tr>
<td><span class="alert">* </span>State</td>
<?php
if($row4['country_name']=="INDIA")
{?>
<td id="statediv"><select name="state_id" class="medforminput" id="state_id" onchange="getCity('select_city.php?state_id='+this.value)">
<option value="">Choose State</option>
</select></td>
<?php else {
<td id="statediv"><input type="text" name="state_id" class="medforminput" id="state_id"/>
</td>
<?php }?>
</tr>
I am getting nothing what wrong in the concept?
I want to display select tag where user choose the "INDIA" else text box to enter the state.
You need to write an onChange event handler in javascript that tests the option selected, then either displays the dropdown or textbox in a dynamic div.
I'm going to use jQuery because it's a LOT less code.
Example:
<select name="country_id" class="medforminput" id="country_id" >
<!-- options go here -->
</select>
<script language="javascript">
$("#country_id").change(function() {
if ($(this).val() == 'India') { // put the country id here instead of string comparison
$("#stateInput").html(getStates());
} else {
$("#stateInput").html("<input type='text' id='stateId' name='stateId' />");
}
});
</script>
Please excuse the pseudocode - I didn't want to make it excessively long.

How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?

I have no experience with jquery and ajax, so far I just looking for source and edit paste the code into my coding. Now I try to look for tutorial autosave combobox selection but i fail to find it.Can someone help me? I only done with MYSQL display record, but I do not know how to auto update combobox selection nito MYSQL using jquery. Example, I want to select booking status, when i choose approve from combobox, it will automatically save into MYSQL without click button submit.
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
//get table contents
$start = ($page-1)*$per_page;
$sql = "SELECT bookingID,eventinfo.eventTitle,boothAlias,testbook.bstatus,date, testbook.username, customer.companyName, customer.contactName from eventinfo, testbook, customer where testbook.username=customer.username AND testbook.eventID=eventinfo.eventID order by date desc limit $start,$per_page";
$rsd = mysql_query($sql);
?>
<form method="post" name="form">
<table width="800px">
<?php
//Print the contents
while($row = mysql_fetch_array($rsd))
{
$id=$row['companyName'];
$contactName=$row['contactName'];
$eventTitle=$row['eventTitle'];
$date=$row['date'];
$status=$row['bstatus'];
$booth=$row['boothAlias']
?>
<tr><td style="color:#B2b2b2; padding-left:4px"><?php echo $id; ?></td><td><?php echo $contactName; ?></td>
<td><?php echo $eventTitle; ?></td><td><?php echo $booth; ?></td><td><?php echo $date; ?></td><td><select name='status' id='status'>
<option value='-1'>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select></td>
</tr>
<?php
}
?>
</table>
</form>
image
do this
<select name='status' id='status'>
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
on saveStatus.php do your mysql update
<?php
$st=$_POST['statusType'];
$qry =" UPDATE tableName SET `tablefield`=$st .. ";
$done = mysql_query($qry);
if($done)
{
echo "Saved Successfully";
}
?>
my first guess would be to use onChange event in select element, eg. <select name='status' id='status' onChange='updateMySQL();'>
in updateMySQL() you could call external script to save data into database. I'm not sure hot to achieve it though, it's just a guess. good luck in finding solution!

php drop down how to control the hide and show

i want to control the drop down box to control show or hide statement. I do like this but it seems it doesn't work, i have it working if im using radio button.
can help me with the code? which part am i wrong?
thank you.
$dbcnx = mysql_connect('localhost', 'root', '');
mysql_select_db('dbase');
if($_POST['gred'])$gred=$_POST['gred'];else $gred="";
<script language="JavaScript">
function funcHide(elemHide1,elemHide2,elemHide3)
{
document.getElementById(elemHide1).style.display = 'none';
document.getElementById(elemHide2).style.display = 'none';
document.getElementById(elemHide3).style.display = 'none';
document.getElementById(elemShow).style.visibility = 'visible';
}
function funcShow(elemShow1,elemShow2,elemShow3)
{
document.getElementById(elemShow1).style.display = 'block';
document.getElementById(elemShow2).style.display = 'block';
document.getElementById(elemShow3).style.display = 'block';
document.getElementById(elemShow1).style.visibility = 'visible';
document.getElementById(elemShow2).style.visibility = 'visible';
document.getElementById(elemShow3).style.visibility = 'visible';
}
</script>
<table>
<tr>
<td>Gred </td>
<td>:</td>
<td><select name="gred" id="gred">
<option value=""> </option>
<option value="A17" <?php if($gred=='A17')echo "selected";?> onClick="funcShow('box1', 'box2', 'box3');">A17</option>
<option value="A22" <?php if($gred=='A22')echo "selected";?>>A22</option>
<option value="A27" <?php if($gred=='A27')echo "selected";?>>A27</option>
</select>
</td>
</tr>
<tr>
<td>TK</td>
<td>:</td>
<td>
<select name="tk" id="tk">
<option value=""> </option>
<option value="01" <?php if($tk=='01')echo "selected";?>>01</option>
<option value="02" <?php if($tk=='02')echo "selected";?>>02</option>
<option value="03" <?php if($tk=='03')echo "selected";?>>03</option>
<option value="04" <?php if($tk=='04')echo "selected";?>>04</option>
<option value="05" <?php if($tk=='05')echo "selected";?>>05</option>
<option value="06" <?php if($tk=='06')echo "selected";?>>06</option>
</select>
<?} ?>
</td>
</tr>
<tr>
<td colspan="2" valign="top">Status</td>
<td valign="top">:</td>
<td>
<?php
$qry = "SELECT * from dtable where userid='".$USER->id."'";
$sql = mysql_query($qry);
$row = mysql_num_rows($sql);
if($row==0)
{
?>
<input type=radio name="status" <?php if($status=='retake') {?>checked="checked"<?php } ?> value="retake" onClick="funcShow('box1', 'box2', 'box3');">Retake<br /></tr> <tr>
<td colspan='2'>
<div id="box1" style="display: none;">Last Date <br> Latest Date<br>
</div></td>
<td><div id="box2" style="display: none;">: <br> : <br></div></td>
<td>
<div id="box3" style="display: none;">
<?php $rsu[lastdate] ?> <br> <?php $rsu[latestdate] ?>
</div>
</td>
don't put the onClick attribute onto the option tag. You should use onChange on the select tag and then pass in this.value. Then based on that value you can decide which "box" to show/hide. Just a simple example:
<script type="text/javascript">
function showHide(selValue){
switch(selValue){
case "A17":
//show/hide whatever box you want.
alert(selValue);
break;
default:
//do nothing
alert('nothing');
}
}
</script>
<select name="gred" id="gred" onChange="showHide(this.value);">
<option value=""> </option>
<option value="A17"<?php if($gred=='A17')echo "selected";?>>A17</option>
<option value="A22" <?php if($gred=='A22')echo "selected";?>>A22</option>
<option value="A27" <?php if($gred=='A27')echo "selected";?>>A27</option>
</select>
for now, as you can tell, it just alerts some values. But it is easy to change.
Use onChange to trigger JS when you change something in the dropdown menu, instead of onClick. With selectedIndex you can determine what has been selected (the option 'show' or 'hide') and go from there.
Tip: get rid of all the junk code and limit it to just the elements that you need. Try to make it work in its most basic form, then build it out to what you're actually trying to do. That way it's a lot easier to track bugs and find out why it's not working.
Also, you might want to look into jQuery. You can do pretty much the same in plain old JavaScript, but jQuery makes things like this a lot easier.

Categories