Dynamic drop down list to fill in a text box - php

I have searched high and low for a resolution to this bus have not been able to work it out. I managed to get this to work when I wanted a dynamic drop down to adjust the values in a second drop down and fill in a text value in a text box.
Now I want to cut out the second step: ie. I actually want to get rid of the second drop down and simply enter a value in the text box. I have tried everything to remove the second step but as soon as I do everything stops working.
At the moment the function looks at the second drop down and sets the options for it and I added the line
document.getElementById('fld_ClientID').value =""
to get it to enter the data in the text box. How do I get rid of the reference to the tblPromotions completely and make it get the data for the text box only.
<script language="javascript">
function setOptions(chosen) {
var selbox = document.myform.selectpromotion;
selbox.options.length = 0;
if (chosen == "0") {
selbox.options[selbox.options.length] = new Option('First select a client','0');
}
<?php
$client_result = mysql_query("SELECT * FROM tblClients ORDER BY ClientName") or die(mysql_error());
while(#($c=mysql_fetch_array($client_result)))
{
?>
if (chosen == "<?=$c['ClientID'];?>") {
<?php
$c_id = $c['ClientID'];
$promo_result = mysql_query("SELECT * FROM tblPromotions WHERE ClientID='$c_id'") or die(mysql_error());
while(#($m=mysql_fetch_array($promo_result)))
{
?>
selbox.options[selbox.options.length] = new
Option('<?=$m['PromotionName'];?>','<?=$m['ClientID'];?>');
document.getElementById('fld_ClientID').value ="<?=$m['ClientID'];?>";
<?php
}
?>
}
<?php
}
?>
}
</script>
</head>
<body>
<form name="myform" method="POST" action="processaddpromotionNEW.php"> ><div align="center">
<p>
<select name="selectclient" size="1"
onchange="setOptions(document.myform.selectclient.options
[document.myform.selectclient.selectedIndex].value);">
<option value="0" selected>Select a client</option>
<?php
$result = mysql_query("SELECT * FROM tblClients ORDER BY ClientName") or die(mysql_error());
while(#($r=mysql_fetch_array($result)))
{
?>
<option value="<?=$r['ClientID'];?>">
<?=$r['ClientName'];?>
</option>
<?php
}
?>
</select>
<br><br>
<select name="selectpromotion" size="1">
<option value=" " selected>First select a client</option>
</select>
</p>
<p>
<input name="fld_ClientID" type="text" class="Arial" id="fld_ClientID" tabindex="11" size="10" />
<br>

maybe, you shouldn't do a mysql query inside a javascript function. you should either:
use ajax to get the possible options
or
query all the possible options once then save it on a global variable
something like:
<script>
var secondOptions = {};
<?php
$promo_result = mysql_query("SELECT * FROM tblPromotions") or die(mysql_error());
while(#($m=mysql_fetch_array($promo_result))){
?>
if(secondOptions['<?=$m['ClientID'];?>'] == undefined)
secondOptions['<?=$m['ClientID'];?>'] = {};
secondOptions['<?=$m['ClientID'];?>']['<?=$m['PromotionId'];?>'] = '<?=$m['PromotionName'];?>';
<?php
}
?>
setOptions(clientId){
jQuery("select[name=selectpromotion]").empty();
options = "";
jQuery.each(secondOptions[clientID],function(a,b){
options += "<option value='"+a+"'>"+b+"</options>";
});
jQuery("select[name=selectpromotion]").append(options);
}
<select name="selectclient" size="1" onchange="setOptions(jQuery(this).val());">
...

Related

Outputting data from database to HTML options and tables

I'm new in PHP.
I have a database with 5 columns. "id" "fldName" "fldPrice" "fldSupplier" and "fldPackage".
I have a HTML table with select options where I output "fldName" where "fldPackage" has a spesific value. I have made this work, but I would also like to output the corresponding "fldPrice" from the selected "fldName" when it's chosen. I'm stuck on how to do this.
This is my php:
<?php
function conTroller(){
include("includes/dbh.php");?>
<?php $sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<option><?php echo $option['fldName']; ?> </option><?php }}
?>
and this is my HTML
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
Can anyone help?
I have been reading, googling and looking for similar problems. The biggest problem for me is that I'm not really sure what to search for.
For the simplicity for only updating price when selectbox changed, I suggest to use DOM Manipulation using Javascript
<?php
function conTroller() {
include("includes/dbh.php");
$sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<!-- add attribute "data-price" so javascript can get price value from the selected option -->
<option data-price="<?php echo $option['fldPrice']; ?>"><?php echo $option['fldName']; ?> </option><?php
}
}?>
<td><b>Electrical package</b></td>
<td>
<!-- add a function in onchange to update price whenever selectbox changed -->
<select id="1" class="custom-select" required onchange="ePkg(event); updatePrice(this)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<!-- add attibute "id" so we can access the element to be updated -->
<td id="price-field">I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
<script>
// function to update price from selected option
function updatePrice(selectbox) {
var price = selectbox.selectedOptions[0].attributes['data-price'].value || '- no price set -';
document.getElementById('price-field').innerHTML = price;
}
</script>
For more advanced flow (eg: getting more product info other than price like description, etc), you will need a separate php file for displaying product info and fetch it using AJAX call. See some tutorial about AJAX and PHP
Steps I did:
PDO is safer.
The first function returns data.
The other is making a presentation.
An additional div with id='fldPrice' will be the place to display the price.
A significant part of the code was done by javascript
function getPackage() {
$db = conn();
$sql = "SELECT id, fldName, fldPrice, fldSupplier, fldPackage FROM tbl_price WHERE fldPackage='controller'";
$sth = $db->prepare($sql);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
function conTroller() {
$options = getPackage();
foreach ($options as $option) {
echo "<option>" . $option['fldName'] . "</option>";
}
}
function ePkg(ev) {
let prices = JSON.parse('<?php echo json_encode(getPackage()); ?>');
let select = document.getElementById('1');
let fldName = select.options[select.selectedIndex].value;
for (let i = 0; i < prices.length; i++) {
if (prices[i]['fldName'] === fldName) {
let d = document.getElementById('fldPrice');
d.innerHTML = 'Prices: ' + prices[i]['fldPrice'];
}
}
}
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>List</td>
<td>Select controller</td>
<div id="fldPrice"></div>

send the selected value from a dropdown menu to another page

I have a dropdownlist populated by a MySql database that shows the titles of books stored in my database.
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
I want the option I choose to send it to another php page search.php
This search.php I want it to get the title and search for this specific book details.(title, price, author.... etc) .I tried to do it with but it ruins the page.
Add below code in form that should work for you.
<form action='search.php' method='post'>
<select id="titles" name='titles'>
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
<input type='submit' value='submit'>
</form>
in search.php:
$title = $_POST['titles'];
You just need to add the form above the select tag and need to give the NAME attribute in the select tag to post the data on another page. You can try with the following code:
<form method="post" action="search.php">
<select id="titles" name="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
<input type="submit" name="submit"/>
</form>
and on the search.php page, you can get the value of the dropdown by this:
$title = $_POST['titles'];
Try as below :
<form method="post" action="YOURPAGEPATH">
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
<input type="submit" name="submit"/>
</form>
Without submit button :
<form method="post">
<select id="titles" onchange="this.form.submit();">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
</form>
Surround that with a form with the appropriate action and add a submit button. Otherwise use something like jQuery to listen for the value of that to change and submit the form.
For example:
<form action="search.php" method="GET">
<select id="titles" name="title">
<?php /* put your stuff here */ ?>
</select>
</form>
And then in jQuery:
$(function(){
$('#titles').on('change', function(){
$(this).closest('form').submit();
});
});
Or you could go real old-school and attach the event listener to the select like this:
<form action="search.php" method="GET">
<select id="titles" name="title" onchange="this.parentNode.submit()">
<?php /* put your stuff here */ ?>
</select>
</form>
Just in case if you don't want to use the Submit Button
<script language="Javascript">
function books(book)
{
var url="http://www.example.com/search.php/?q="+book;
window.open(url, "_self");
}
</script>
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option onClick="books('.$row['title'].')" value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
Here the list will call the Books function on Click and pass the arguments to the function which will redirect you to search.php
To retrieve the book name use
$_GET["q"]
Change the URL as required.
And if the problem is solved don't forget to Mark the answer.

Select from drop-down menu and reload page

I've got a table that populates data from a MYSQL database and populates a drop-down menu from the same database. I have the drop down menu and table just fine, I would like to be able to choose which data I show in the table however.
<select name = 'peer-id' method='post' style = 'position: relative'>
<?php
while ($content = mysql_fetch_array($peer)) {
echo "<option value='" . $content['Peer'] . "'>" . $content['Peer'] . "</option>";
}
$results = mysql_query("SELECT Destination FROM rate ");
?>
</select>
That's what I have for the select box. How can I get the choice from that and save that as a variable and refresh the table data?
I need to clarify that this will change that current data
#Data#Data#Data
#Data#Data#Data
#Data#Data#Data
Then choose drop down choice and I want it to show new data
#Data2#Data2#Data2
#Data2#Data2#Data2
#Data2#Data2#Data2
So it's going to need to load a new page or refresh some how because it's changing via PHP and not javascript.
I think form may be better, for example
<form id="myform" method="post">
<select name = 'peer-id' style = 'position: relative' onchange="change()">
<option value="1">12</option>
<option value="2">15</option>
<option value="3">16</option>
<option value="4">18</option>
</select>
</form>
<script>
function change(){
document.getElementById("myform").submit();
}
</script>
In the above code, whenever you change the value of select, it will post to the backend, then according to the posted value, you can do want you want, to get the peer-id in php, you can use the following code
$peer-id = $_POST['peer-id'];
Hope helps!
apply this code in select tag hope this works
<select onchange="location = this.options[this.selectedIndex].value;" style="text-decoration:none;">
<option value="customers.php"></font></option>
</select>
insted of the static options, you can do it like this :) here you get all the options from the database. Just replace it with the static options
$peer = mysql_query("SELECT Peer FROM rate Group By Peer Where peer = 'variable'");
$result_peer = mysql_query($peer);
if($result_peer){
while($row_peer = mysql_fetch_array($result_peer)){
echo'<option value='.$row_peer['Peer'].'>'.$row_peer['Peer'].'</option>';
}
I agree in using form, and with this you can echo back onto the page with a submit button (code tested):
<form id="myForm" method="POST">
<select name="select" onchange="<?php echo $_SERVER['PHP_SELF'];?>">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<input type="submit" name="formSubmit" value="Submit" >
</form>
<?php
if(isset($_POST['formSubmit']) ){
$var = $_POST['select'];
$query = "SELECT * FROM table_name WHERE DesiredField='$var'";
$result = mysql_query($query)
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$var2 = $row['FieldName'];
echo "First field: " . $var2 . "<br>";
// and so on for what you want to echo out
}
}
?>

PHP: Echo value of selected item from a dependable dropdown menu

I am currently working with a Dependable dropdown menu that functions with the help of jQuery and PHP. The values are being pulled of MySQL database. Is there away to php echo the selected value of a dependable drop down menu?
EXAMPLE
HTML/PHP
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Please add jquery.js.
your html code
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
//jquery code for source list
<script type="text/javascript">
$(document).ready(function(){
$('#gender').change(function() {
if ($(this).val()!='') {
$("#category").load("postfile.php",{gender_id: $(this).val()});
$("#category").removeAttr('disabled');
}
});
//code on change of sel_source
$('#category').change(function() {
if ($(this).val()!='') {
$("#colour").load("postfile.php",{category_id: $(this).val()});
$("#colour").removeAttr('disabled');
}
});
});
</script>
//postfile.php
//your mysql connection other things goes here
//code for category
$objDb = new PDO('mysql:host=localhost;dbname=dbname', 'ur_username', 'ur_password');
if(isset($_REQUEST['gender_id']) && !empty($_REQUEST['gender_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['gender_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
//code for color
if(isset($_REQUEST['category_id']) && !empty($_REQUEST['category_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['category_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
Hope this will help you.
You are going to have to write a JavaScript function that retrieves the selected value or option from the first HTML select field. This function commonly writes out a new URL path to the current page with the addition of some concatonated Get Variables:
<script type="text/javascript">
getSelectedOptionValue() {
// create some variables to store your know values such as URL path and document
var myPath = " put the URL path to the current document here ";
var currentPage = "currentPage.php";
// get the values of any necessary select fields
var carMake = document.getElementById("carMake").value;
// write out the final URL with the Get Method variables you want using concatnitation
var getMethodURL = myPath + currentPage + "?carMake='" + carMake + "'";
// function refreshes page using the function made URL
window.location.replace( getMethodURL );
}
</script>
Since the second select field is dependent on the first you have to assume that the user is going to make a selection from the first choice of options. This means that the function that retrieves the value of the primary select field must run in response to a change in the fields selection. For example
<select name="carMake" id="carMake" onchange="getSelectedOptionValue();">
Depending on how you have set up your DB, you may want either the value of the option tag or the string presented to the user between the option tags...this is up to you keeping in mind how you may re-query the information if your original record set hasn't already pulled up the necessary info to write the second set of select option tags.
To write out the second select field using php simply repeat the while loop you have used for the first. This time replace your SQL statement with a new one using a variable in which you have stored the value retrieved from the new URL using the get method
<?php
// here I am using the more generic request method although you could use the get as well
$carMake = $_REQUEST['carMake'];
sql_secondSelectField = "SELECT * FROM tbl_carModels WHERE carMake = $carMake";
// Run new query and repeat similar while loop used to write your first select field ?>

How to get the value against the value selected in text box?

I want to know that when I select any value from dropdown box it shows it's price in next field.
Example: if I select snacks from the dropdown menu then it show its price in next field by fetching its price from database in PHP. Items are also fetched from database.
Here is how I want when select a particular value:
Here is the code for fetching data from the database:
<?php
$eb = "SELECT EmployeeID,FirstName,LastName FROM employees";
$res = mysql_query($eb);
$no_records = mysql_num_rows($res);
if($no_records > 0)
{?>
<select name="EnteredBy" id="EnteredBy"><?php
while($row = mysql_fetch_array($res))
{
echo '<option value='.$row['EmployeeID'].'>'.$row['LastName'].",".$row['FirstName'].'</option>';
}
?>
</select>
<?php
}
?>
Something like the following should help you out. All you need to do is write an onchange function to update your "next field" with the value of the option selected.
<html>
<head>
<script type="text/javascript">
function changeValue() {
var price = document.getElementById('items').options[document.getElementById('items').selectedIndex].value;
document.getElementById('price').innerHTML= '$'+price;
}
</script>
</head>
<body onload="changeValue();">
Select Item:
<select id="items" onchange="changeValue();">
<option value="5">Snack</option>
<option value="1">Soda</option>
<option value="10">Meal</option>
</select>
<br/><br/>
Price:
<div id="price">
</div>
</body>
</html>

Categories