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']
Related
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?
I am trying to pass a variable, a first name with an apostrophe, from HTML to jQuery. By the time the value gets to jQuery, the string is missing all the characters after the apostrophe.
Name Example: Test'Ing
This is part of the form. I fill the list dynamically and the name appears correct when pulled from the database:
<?php echo "<select id='hiringManager' class='dropdown_form' name='hiringManager'>";
echo "<option disabled selected>Hiring Manager</option>";
while ($result_row = mysqli_fetch_row($hiring_manager_query)) {
echo "<option value='" . $result_row[0] . "'>" . $result_row[0] . "</option>";
}
echo "</select>" ?>
And then I get the value from the form and display it in a jQuery modal for confirmation:
$('#hiringManagerModal').text($('#hiringManager').val());
The resulting text shown is:
"Test" instead of "Test'Ing"
I have poked around but have not been able to find a post that addresses this, or I could not be phrasing the issue correctly in the search.
Any help is appreciated. Thanks!
The problem is with the PHP code. I have replaced the 's with "s and "s with 's. The outputted HTML earlier was,
<select id='hiringManager' class='dropdown_form' name='hiringManager'>
<option disabled selected>Hiring Manager</option>
<option value='test'ing'>test'ing</option> <!-- In this option, the value is test instead of test'ing -->
</select>
and now after all the replacements, it is,
<select id="hiringManager" class="dropdown_form" name="hiringManager">
<option disabled selected>Hiring Manager</option>
<option value="test'ing">test'ing</option><!-- Now, here the value is test'ing, as required -->
</select>
What really happens is that when ' is encountered, the string gets terminated and as a result only "test" gets outputted instead of "test'ing".
The corrected PHP code after all the replacements:
<?php
echo '<select id="hiringManager" class="dropdown_form" onchange="displayInModal();" name="hiringManager">';
echo '<option disabled selected>Hiring Manager</option>';
while ($result_row = mysqli_fetch_row($hiring_manager_query)) {
echo '<option value="' . $result_row[0] . '">' . $result_row[0] . '</option>';
}
echo '</select>'
?>
with,
$('#hiringManagerModal').text($('#hiringManager').val());
Now, the same problem would arise with
<option value="test"ing"></option>
Other way:
echo '<option value='test\'ing'></option>';
so I make a small php app and I try to use ajax.
I have two lists :
<select name="auteur" id="auteur" >
<option value='-1'>Aucun auteur</option>
<?php
require("bd/bd.inc.php");
$resA = listeAuteurs();
while ($rowA = $resA->fetch()) {
echo "<option value='" . $rowA["id"] . "'>" . $rowA["nom"] . "</option>";
}
?>
</select>
And
<select id="livre" name="livre">
<option value="-1">
Aucun livre
</option>
<?php
$idAuteur = NULL;
require("bd/bd.inc.php");
$resL = listeLivres($idAuteur);
while ($rowL = $resL->fetch()) {
echo "<option value='" . $rowL["idLivre"] . "'>" . $rowL["titre"] . "</option>";
}
?>
</select>
In my ajax.js file I get the value of the slected option of the first list with this code :var validauteur = $( "#auteur" ).val();
And what I want is to modify the value of the variable "$idAuteur" in the second list with the value of the selected option of the first list.
Hope you can help.
You can't use AJAX to edit the PHP variable of a page that has already loaded - but you can use AJAX to trigger a JS function (on success) which will edit the second input.
In your AJAX success return, add some JS code to edit the second select box:
$( "#livre" ).html(...);
What you actually want to change it to is upto you.
Hi I am trying to create a set of drop down boxes that will use an array of data from the values that you pick and then runs through a loop to post them to the screen at the moment the data that i want to use will just be local but i want to edit this later so that it will loop through the data from my database and post that to the screen. i have looked at other questions on this subject and just wondering how i would change it for my code i have looked at this link questions on stack overflow that I have looked at i have just got a couple questions that im wondering if anybody has seen this before or if they have seen any examples i have also looked at for loops and i understand the concept
my questions to you are:
1) how would I post the values from my drop down boxes into a php array
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
3)Would I need to use a second language like javascript or can it be done just in php
My drop down box code is
<div id="Content">
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="%">any...</option>
</select>
<br /><br />
Choose a principle:<br />
<select id="principle">
<option value="%">any...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<!-- end of the Options -->
below is the select.class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM subject";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['subject_id'] . '">' . $row['description'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM section WHERE subject_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['section_id'] . '">' . $row['description'] . '</option>';
}
return $type;
}
public function ShowPrinciple()
{
$sql = "SELECT * FROM principle WHERE section_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$principle = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$principle .= '<option value="' . $row['principle_id'] . '">' . $row['description'] . '</option>';
}
return $principle;
}
}
$opt = new SelectList();
?>
1) how would I post the values from my drop down boxes into a php array
In the form tag add method="POST". Reference in PHP with $_POST array. Make sure to validate and escape the data before writing to your DB.
2) how would I then check the values against and array of data and then choose which are correct and post them to the screen.
If you don't have millions of categories, you are better off sending them all as a JSON array and using Javascript. Something like:
<script>
var categories = <?php echo json_encode($opt->ShowCategory()); ?>;
</script>
json_encode may require some options to be set, depening on your character set. More info here: http://php.net/manual/en/function.json-encode.php
Making a new request each time someone changes a dropdown box will drive them crazy, I know I hate that. If you have used jQuery before, this is very easy. This isn't that difficult without it.
3)Would I need to use a second language like javascript or can it be done just in php
For the sake of your users, use Javascript.
code for showCategory()
...
$categories = new array();
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$categories[$row['subject_id']] = $row['description'];
}
$validCategories = $this->getValidCategories() // get the valid categories
foreach($categories as $index=>$cat){
// only choose the categories that are valid
if(array_search($cat,$validCategories) !== FALSE)
$category.= '<option value="'.$index.'">'.$cat.'</option>';
}
return $category;
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>';