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>
Related
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>
Hello all: i have 2 dropdowns list that populate themselves from two different TABLES.
The first TABLE
(ID|Project_Name|isActive).
And the second TABLE is for users
(Project_Id|Name)
I want to show the options from the second dropdown according on what is selected from the first one.
For example in the first TABLE i have 3 Projects:
1:Project1
2:Project2
3:Project3
And on the second TABLE which is for users: The user has an id that depends on the project from first TABLE:
User A works on Project1
User B works on Project1
User C works on Project2
<html>
<body>
<script type="text/javascript">
function changeProject()
{
alert(document.getElementById("ProjOptionId_id").value);
}
</script>
<form method="POST" action="page.php">
<table>
<tr>
<td>
<?php Insertprojects(); ?>
</td>
</tr>
<tr>
<td>
<?php InsertUsers(); ?>
</td>
</tr>
<form>
</body>
</html>
<?php
function Insertprojects()
{
$Search ="SELECT * FROM proj_database";
$query= mysql_query($Search);
echo "<select name=\"ProjOptionId\" id=\"ProjOptionId_id\" onchange=\"changeProject()\">";
$bFirstLoop=0;
while($Row = mysql_fetch_array($query))
echo "<option value=\"$Row[ID]\">$Row[Project_Name]</option>";
if($bFirstLoop==0)
{
$GLOBALS['sProjectId'] = $Row['ID'];
}
$bFirstLoop++;
}
echo "</select>";
}
?>
I made the javascript function to get the index of the dropdown, so i can change the second dropdown depending on the element selected.
How can i do when you select Project1 on first dropdown, to appear in second dropdown the users that works only with Project1 and so on without reloading the page.
I manage to solve this by jQuery:
$(function()
{
$("#projectSelector").change(function()
{
$("#customerSelector").load("getter.php?project_id=" + $("#projectSelector").val());
});
});
Where this is my first dropdown:
<select id="projectSelector" name="projectSelector">
<option selected value="base">--Select an option--</option>
<?php
/*Code to populate from Mysql query
SELECT* FROM......*/
?>
</select>
and the second dropdown that takes the value according on what is selected from first one
<select id="customerSelector">
<option>--Select an Option--</option>
</select>
and the getter.php is an external files that contains a varible to use when the dropdown value changes:
<?php
$sProjectId = $_GET['project_id'];
mysql_query = SELECT * FROM database1 WHERE tablecolum = $sProjectId;
while ($row = mysql_fetch_array($result)
{
echo "<option>".$row['tablecolumn']."</option>";
}
I have three select tags (1)Category, (2)Sub-Category, (3)Product Description and I want to fill it with data from database. But what I want is to when I select eg. Office Supplies from the Category on the Sub Category will only display eg. Ballpen, Ruler, Notebook and when I select eg. Ballpen on the Product Description will only display the description of the Ballpen. Btw I had created some code made from PHP but it only fills the select tags. I hope someone will help me. This is for out Thesis. :)
<html>
<head>
<title>Test Select</title>
</head>
<body>
<?php
$query = "SELECT DISTINCT(`product_cate`) FROM `tbl_product` ";
$result = mysql_query($query);
?>
Category:
<select id="select1">
<option></option>
<?php while($data = mysql_fetch_array($result)){
$displayData = $data['product_cate'];
?>
<option value="<?php echo $displayData;?>"><?php echo $displayData; ?></option>
<?php } ?>
</select>
<?php
$query2 = "SELECT DISTINCT(`product_sub`) FROM `tbl_product`";
$result2 = mysql_query($query2);
?>
Sub Category:
<select id="select2">
<option></option>
<?php while($data2 = mysql_fetch_array($result2)){
$displayData2 = $data2['product_sub'];
?>
<option value="<?php echo $displayData2;?>"><?php echo $displayData2;?></option>
<?php }?>
</select>
<?php
$query3 = "SELECT DISTINCT(`product_desc`) FROM `tbl_product`";
$result3 = mysql_query($query3);
?>
Product Description:
<select id="select3">
<option></option>
<?php while($data3 = mysql_fetch_array($result3)){
$displayData3 = $data3['product_desc'];
?>
<option value="<?php echo $displayData3;?>"><?php echo $displayData3;?></option>
<?php }?>
</select>
</body>
</html>
General guide on the path to take would be to use jquery. Basically what will happen is that you'll load the first select ie Category. When the user selects a category, the change should fire up an ajax call to query the db and get sub directories from the category id posted. the call returns the sub category as json which you'll put in the select box. same plan for the product description
This can be a starting point and follow up from there:
jQuery dropdown dependent
Lots of similar questions here
You can just link options with an other attribute for example :
<select class="cat"><option>Category<option><select>
<select class="sub_cat"><option data-cat="Category">Sub-Category<option><select>
after that use can use javascript to hide unwanted categories for example (with jquery) :
$('.cat').change(function() {
$('.sub_cat option:not([data-cat="Category"])').hide();
});
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());">
...
I'm new in PHP.. I need your help..
I have 2 dropdownlist that related:
dropdown 1 : manually insert the value
dropdown 2 : attach value from database (value based on condition that selected in dropdown 1)
Then, both value which are selected will display in textbox at another form.
My problem is:
1) The value in 2nd dropdown can't be display.
2) The value in 1st dropdown can pass to other form but the 2nd can't.
Please kindly guide me.
I don't know how to share my code here.
form1.php
//1st dropdown
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;" onchange="loadXMLDoc(this.value); ">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
//2nd dropdown
$fruit_name = $_POST['fruit_name'];
#Connect to MySQL
#Connect to database
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = ''>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
//Closes specified connection
?>
form2.php
<?php
//connection
$fruit_name = $_POST['fruit_name'];
$colour = $_POST['colour'];
?>
<label>
<input type="text" name="fruit_name" id="fruit_name" value = "<?php echo $fruit_name;?>" readonly>
</label>
<p>
<label>
<input type="text" name="colour" id="colour" value="<?php echo $colour;?>" readonly>
</label>
</p>
I usually don't do this but since I've some spare time on hand right now, I'm going to give the general approach that you can follow:
Include the following between your <head> tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
Below that, paste this code
<script type="text/javascript">
$(function(){
$('select#fruit_name').change(function(){
var selectedVal = $(this).val(); // get the selected value
$.ajax({ // send ajax request to the php file to process data
type:'post',
url:'php-page-name.php',
data:{'value':selectedVal},
success:function(ret) // display the result from php-page-name.php page
{
$('div#result').html(ret);
}
});
});
});
</script>
Lets move on to your HTML now
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
</select>
<div id="result">
<select>
<option>Select One</option>
</select>
</div>
php-page-name.php page (Do not forget to create this page and put it in the same folder as form1.php)
<?php
// put the code to connect to your database here
$fruit_name = $_POST['value']; // this will contain the value selected from first dropdown
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['colour']."'>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
?>
PS : I'm using the mysql_* functions in this example since I'm assuming you're too. But this is not recommended as they are going to be deprecated soon. You might want to switch to mysqli or PDO