i have a select option, after selecting a brand I successfully get/display the brand name but I want also the other values be displayed like price, with or without refreshing the page.
<?php
require_once 'config.php';
echo '<select class="form-control action" name="tran_description" value="<?
php echo $tran_description; ?>" style="background-color:#F0F0F0">';
$sql = mysqli_query($mysqli, 'SELECT * FROM products order by product_id');
while ($row = $sql->fetch_assoc()){
echo '<option id="' . $row['product_id'] . '"';
echo ' value="' . $row['description'] . '" ';
echo ' value="' . $row['price'] . '" ';
if($row['description'] == $tran_description) {
if($row['price'] == $tran_price) {
$tran_price = $row['price'];
echo ' selected="selected"';
}
}
if($row['product_id'] == $row['description']) {
echo ' selected="selected"';
}
echo '>';
echo $row['description'];
echo '</option>';
}
echo '</select>';
?>
I can get the value of the description but the price I couldnt. In one select option representing the brand or description I want also the price value of that brand I selected be assign to a variable so I can do arithmetic operation in the back code without seeing it.Thanks.
You are using wrong HTML structure only the first attribute is being used while the other is being ignored in the DOM .The right way to store multiple values in a single select can be like this:
<select name="">
<option value="{'num_sequence':[0,1,2,3]}">Option one</option>
<option value="{'foo':'bar','one':'two'}">Option two</option>
</select>
In your case it should be like this:
echo '<option id="' . $row['product_id'] . '"';
// echo ' value="{ /"description:/"' . $row['description'] . ', /"price:/"' . $row['price'] . ' }" ';
echo ' value="' .
json_encode(['description'=>$row['description'], 'price'=>$row['price']) .
'">";
Then to get the value you'll do is:
$description = $_POST['NameOfSelectInput']['description'];
$price = $_POST['NameOfSelectInput']['price'];
If you want to get the value in javascript, using jQuery, for example, you could do:
var value = JSON.parse($('#select_id').val()); // use id of your select control
var price = value.price;
var description = value.description;
You should do appropriate error checking...
For more details refer here:
Can an Option in a Select tag carry multiple values?
Related
I have a dropdown <select> HTML menu created from a MySQL table using PHP. Each <option> value contains a socket, I have a HTML table created from a MySQL table using PHP which contains a column "Socket". I want to filter the table to only show matching sockets to the one selected in the <select> menu.
I have tried modifying Javascript search code to no success.
The code for the table creation is:
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td><a href='https://au.pcpartpicker.com/product/".$row["id"]."' target='_blank'>" . $row["name"]. "</a></td><td>" . $row["price"]."</td><td>" . $row["socket"]."</td><td>" . $row["chipset"]."</td><td>" . $row["ramslots"]."</td><td>" . $row["maxram"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
The code for the <select> menu is:
$sql = "SELECT name, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value='CPU'>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='".$row["socket"]."'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
Here is the link to the entire webpage code: pastebin.com/WztPQzRG
cpu SQL fiddle: db-fiddle.com/f/teZxiaduNVjuYCj1pWjj73/0
motherboard SQL fiddle: db-fiddle.com/f/pSs8yKNrgTqtiwdTbmWcg/0
Update: Here is my PHP
$sql = "SELECT name, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value=''>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["socket"] . "'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr data-socket="'. $row['socket'] . '"><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['socket'] . '</td><td>' . $row['chipset'] . '</td><td>' . $row['ramslots'] . '</td><td>' . $row['maxram'] . '</td></tr>';
}
echo "</table>";
} else {
echo "0 results";
}
Update 2:
I have tried troubleshooting by adding:
echo "<option value='AM4'>AM4</option>";
echo "<option value='LGA1151'>LGA1151</option>";
And
echo "<tr data-socket='AM4'><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
However nothing happens still. All I can think is the script isn't added right or something; here it is:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tr[data-socket]').show();
if (socket.length) {
$('tr[data-socket!="' + socket + '"]').hide();
}
});
</script>
</body>
</html>
What other troubleshooting steps can I take?
I need to get a Javascript function which runs whenever a new option is selected from the <select> menu, the function needs to get the selected <select> menu socket name then loop through each row in the table and check if the socket matches, otherwise hide the row.
Start by adding something into the table row to identify the socket. Let's use a data attribute:
echo '<tr data-socket="'. $row['socket'] . '"><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['socket'] . '</td><td>' . $row['chipset'] . '</td><td>' . $row['ramslots'] . '</td><td>' . $row['maxram'] . '</td></tr>';
Also change your default option line to this
echo "<option value=''>CPU</option>";
I'm going to suggest that you use jQuery because it's going to make your life easier. So add just before the close of your body tag
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then you need to create a listener for the select to change and then hides anything that doesn't match the selected CPU socket. Put this right AFTER the script tag above that included the jQuery library.
<script>
$(function() {
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tr[data-socket]').show();
if (socket.length) {
$('tr[data-socket!="' + socket + '"]').hide();
}
});
});
</script>
I have a drop down list that is populated by calling another PHP file who's values are taken from a database. The functionality works but I would like to retain the value selected once the onchange form submit happens.
I have had success by using the following for a static lists but not sure how I can get it to work for a dynamic list that is obtained from a database
<option value="company" <?php if($_GET['sort']== 'company') echo 'selected="selected"';?>>Company</option>
Here is the HTML code for the select
<select name="client" id="client" onChange='this.form.submit()'>
<option value="default"></option>
<option value="all">----- ALL CLIENTS -----</option>
<?php
include("sql_clients.php");
?>
And here is part of the the sql_clients.php code
if (sqlsrv_has_rows($result)) {
while( $row = sqlsrv_fetch_array($result))
{
echo ('<option value="' .$row[CompanyName] . '">' . $row['CompanyName'] . "</option>" ."\n" ."\t" ."\t" ."\t" ."\t" ."\t");
}
}
Thanks
Its the same thing, just now instead of one hardcoded value, use the variable:
while( $row = sqlsrv_fetch_array($result))
{
echo '<option value="' .$row['CompanyName'] . '"';
if($_GET['sort']==$row['CompanyName'])
{
echo ' selected="selected"';
}
echo '>' . $row['CompanyName'] . "</option>" ."\n" ."\t" ."\t" ."\t" ."\t" ."\t";
}
Also $row[CompanyName] should be $row['CompanyName']
I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D
I am have this issue:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do.
The second select list is empty initially.
I want to fill it with values depending of what is chose in first select list.
How can I do that? To fill the second select list only if something is selected in first select list.
MrCode has a nice example for you.
Using Ajax To Populate A Select Box
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with
The best way to handle this would be to populate the list after you made a change on the first list. For example.
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. for example your some.php will take a value parameter. The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}]. Please keep this in mind.
The tables in test.html are getting create dynamically on a button click add event. The var i is further up in the script.
The html runs and and allows me to select a value from service selection (The selection in the first drop down should simply return a 0,1,2). The value of the selection is passed onto support/descriptions.php via a post, a mysql query is made and I hope to return the result array back to the selection called description. I currently get no values on the alert of the array or vales back to the second selection, but I get no errors either. Do you see anything in the php file preventing the array from getting filled? What is the reason the div for the second drop down is not getting filled either?
The second alert returns a message with the following:
<option value="Array">Array</option>
<option value="Array">Array</option>
<option value="Array">Array</option>
<option value="Array">Array</option>
<option value="Array">Array</option>
test.html
$(document).on('change', '.service', function () {
var element = $(this);
var I = element.attr("id");
$.post("support/descriptions.php", {
id: $(this).val()
},
function (data) {
var response = (data).split(";", 2);
alert(response[0]);
alert(response[1]);
$("#descript" + I).html(response[1]);
});
return false;
});
<table>
<th>Catagory</th>
<th>Select Item</th>
<tr>
<td>
<select class ="service" name="service' + i + '" id="' + i + '">
<option value="0">Select One</option>
<option value="1">Hardscape</option>
<option value="2">Plants</option>
</select>
</td>
<td>
<select name="description' + i + '" id="' + i + '"><div id="descript' + i + '"></div></select>
</td>
</tr>
</table>
descriptions.php
<?php
include('db_connection.php');
$id = $_POST['id'];
if ($id == 1){
$result = mysql_query("SELECT Distinct description FROM hardscape");
}
if($id == 2){
$result = mysql_query("SELECT Distinct description FROM plants");
}
$options = '<option value="Select One">Select One</option>';
while($row = mysql_fetch_array($result)) {
$options .= '<option value="'. $row['description'] .'">'. $row['description'] .'</option>';
}
echo $id .";".$options.";";
?>
UPDATE -
My issue with the array not getting populated is because I was using ";" as a parse. I found that my data had ";" in them so for testing I changed
echo $id .";".$options.";";
to
echo $id ."~".$options."~";
I also change my div from the inside to the outside
<select name="description' + i + '" id="' + i + '"><div id="descript' + i + '"></div></select>
to
<div id="descript' + i + '"><select name="description' + i + '" id="' + i + '"></select></div>
Last but not least I had to change my php file to the following to rebuild the whole selection:
$options = '<select><option value="Select One">Select One</option>';
while($row = mysql_fetch_array($result)) {
$options .= '<option value="'. $row['description'] .'">'. $row['description'] .'</option>';
}
$options .='</select>';
echo $options;
$row is an array, to get the field description you have to get it from the array, $row['description']
$options .= '<option value="'. $row['description'] .'">'. $row['description'] .'</option>';