Retain Data Recieved from Database on HTML form - javascript

<?php
include_once 'database_connect.php';
$conn = new dbconnection();
$dbcon = $conn->connect();
if (!$dbcon) {
die("Fail".mysqli_error($dbcon));
}
?>
<html>
<head>
<title></title>
<script type="text/javascript"></script>
</head>
<body>
<form name="frm" method="post" action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<table width="50%" border="1" cellpadding="3" cellspacing="3" align="center">
<?php
$value1 = array();
$select_query = "SELECT Distinct branch FROM subjects";
$result = mysqli_query($dbcon, $select_query);
if (!$result) {
die("Fail".mysqli_error($dbcon));
}
while ($row = mysqli_fetch_array($result)) {
$value1[] = $row['branch'];
}
?>
<tr>
<td>Branch
<td><select name="branch" id="branch" onchange="document.frm.submit();">
<option>Select Branch</option>
<?php
foreach ($value1 as $gets)
echo "<option value={$gets}>{$gets}</option>";
?>
</select>
<?php
$value2 = array();
if (isset($_POST['branch'])) {
$branch = $_POST['branch'];
$getsub_query = "SELECT sub_code FROM subjects where branch='$branch'";
$result2 = mysqli_query($dbcon, $getsub_query);
if (!$result2) {
die("Fail\n".mysqli_error($dbcon));
}
while ($row1 = mysqli_fetch_array($result2)) {
$value2[] = $row1['sub_code'];
}
}
?>
<tr>
<td>Subject Code
<td><select name="subcode" id="subcode">
<option>Subject Code</option>
<?php
foreach ($value2 as $gets)
echo "<option value={$gets}>{$gets}</option>";
?>
</select>
This code gets the first drop down list branch from data base. When we select value from it, second drop down list get filled from database . but problem is when i select option in first drop down list, the selected option does not remain their in first drop down list . but second drop down list fills correctly. i want that option i have selected should remain selected. Like its state should be changed. I think first drop down list gets filled again on form load.

You have to mention in your html that the option is indeed selected.
Try replacing
echo "<option value={$gets}>{$gets}</option>";
By
$selected = '';
if (isset($_POST['branch'] && $gets==$_POST['branch']) {
$selected = ' selected="selected"';
}
echo "<option value={$gets}".$selected.">{$gets}</option>";

Related

How can I get data to input from my select option

The options for the select menu are created from a database. I want to print the value of the selected option on the input. The code below only prints the first option value. I want to print them all. thanks.
<?php
$sql2 = "select * from add_meta";
$sonuc2= $conn->query($sql2);
if($sonuc2->num_rows>0){
while($kayitlar2 = $sonuc2->fetch_object()){
if($kayitlar2->isim!="Renk")
{
?>
<select id="selectid" name="<?php $kayitlar2->isim; ?>" class="sec" onchange="degergoster()" >
<option id="barkodd" value="" style="display:none;"><?php echo $kayitlar2->isim; ?> seçin</option>
<?php
$sql = "select * from add_barkod where kat_list in('$kayitlar2->isim')";
$sonuc= $conn->query($sql);
if($sonuc->num_rows>0){
while($kayitlar = $sonuc->fetch_object()){
?>
<option name="selectname1" value="<?php echo $kayitlar->ekle_hane;?>"><?php echo $kayitlar->ekle_isim; }} ?></option>
</select>
<?php
} }}
?>
<input id="e" name="varyantkod" class="sec">
Javascript code:
function degergoster() {
var selectkutu = document.getElementById("selectid");
var selectkutu_value = selectkutu.options[selectkutu.selectedIndex].value;
document.getElementById("e").value=selectkutu_value;
}
just get the value of the select object and add that to the value of the input
change
document.getElementById("selectid");
to
document.getElementById("selectid").value;
This should work

Select dropdown option and display table (javascript)

With a SELECT query I obtain an array of 7 names, create a dropdown list and each name is a table which is then hidden.
I want to click on the name in the dropdown list and display the table.
I am not receiving any errors but the following code only displays the first table in the array no matter what option is selected. I have little knowledge of javascript and the function has been cobbled together from various queries on the site.
Javascript:
function changeOpt(clicked) {
var x = document.getElementById("optChange");
var optVal = x.options[x.selectedIndex].value;
for(var i =0; i<x.length;i++){
if(optVal = document.getElementById('datath'))
document.getElementById('data').style.display = 'block';
}
}
HTML/PHP:
while($row = mysqli_fetch_array($result))
{
$array = $row;
//echo '<pre>'.print_r($array).'</pre>';
echo '<table id="data" style="display:none;">';
echo '<tr><td>You searched for:</td></tr>';
echo '<tr><th id="datath">'.$row[0].'</th><th>'.$row[1].'</th><th>'.$row[2].'</th>';
echo '</tr>';
echo '</table>';
$option .= '<option value = "'.$row['1'].'">'.$row['1'].'</option>';
}
?>
<form method="post" action="#" id="my_form" >
<select id="optChange" name="opt" onchange="changeOpt(this.id)">
<option><--select a name--></option>
<option><?php echo $option; ?></option>
</select>
<input type="button" name="submit" value="submit" >
</form>
Am I completely off-beam ? Can someone give me some guidance please to get my code straight.

How to get value from dynamically filled drop down on button click in php

I am stuck in getting value from drop down. Drop down is dynamically filled from sql server database.
Dropdown 1 displays product name and it is dynamically filled.
Dropdown 2 displays environment name and it is filled by HTML.
I am getting value of environment but not product.
Please help me. Thanks
Here is the code:
<form action="" method="post">
//Dropdown 1
<p>Product Name:
<select name="productname">
<option value="">Select</option>
<?php
if( $conn )
{
$sql_dd = "SELECT ProductName from Product";
$stmt = sqlsrv_query( $conn, $sql_dd );
if( $stmt === false) {die( print_r( sqlsrv_errors(), true) );}
$rows = sqlsrv_has_rows( $stmt );
if ($rows === false)
echo "There is no data. <br />";
else
{ while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
echo "<option value=''>".$row['ProductName']."</option>";
}
}
?>
//Dropdown 2
Client Type:
<select name="environment" style="width: 10%;">
<option value="">Select</option>
<option value="en1">en1</option>
<option value="en2">en2</option>
<option value="en3">en3</option>
</select> 
<input type="submit" class="theme-btn" value="Search" name="submit"/>
<?php
if(isset($_POST['submit']) )
{
$productname = $_POST['productname'];
$environment= $_POST['environment'];
echo "productname: ".$productname." environment: ".$environment;
}?>
The value is not added
this:
echo "<option value=''>".$row['ProductName']."</option>";
should be
echo "<option value='" . $row['ProductName'] . "'>". $row['ProductName'] ."</option>";

checked checkbox will remain through pagination

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

how to put selected item in dropdown list

I am creating a dropdown list in php. how can i put the selected item when someone selects an item.
my php code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<select name="app" id="dropdown" value="" onchange="this.form.submit()" ><option>--select-app--</option>
<?php
$sql="select * from application";
$result=mysqli_query($con, $sql) or die("ereor selecting app ".mysqli_error($con));
while($row=mysqli_fetch_array($result))
{
$selected = $row['name'];
echo "<option id=". $row['id']."value = ".$row['id'].">".$row['name']."</option>";
}
echo "</select>";
?>
i want this: if I select an item it will show it as selected. how can I do this
You can do it in php like
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<select name="app" id="dropdown" value="" onchange="this.form.submit()" >
<option>--select-app--</option>
<?php
$sql="select * from application";
$result=mysqli_query($con, $sql) or die("ereor selecting app ".mysqli_error($con));
$selected_val = $_POST['app']; //Should be $_GET, $_POST, $_SESSION whatever your selected value is
while($row=mysqli_fetch_array($result))
{
if(trim($row['id']) == trim($selected_val)) //<== Change this line
$selected = 'selected="selected"';
else
$selected = '';
echo '<option id="'. $row['id'].'" value="'.$row['id'].'" '. $selected.'>'. $row['name'] .'</option>';
//^Change this line
}
echo "</select>";
?>
In jQuery you can do it like
$('#dropdown').val('<?php echo "My val"; //The value goes here ?>');
Assuming that you mean you want to retain the selection after the form is submitted, you can do this inside the while loop:
$selected = (isset($_POST['app']) && $_POST['app'] == $row['id'] ? 'selected' : '');
echo "<option id=".$row['id']." value = ".$row['id']." ".$selected.">".$row['name']."</option>";

Categories

Resources