I'm having trouble setting the value of the dropdown after the form input refreshes the page. I can get the value but no matter what I try I'm unable to set the dropdown after the page refreshes. I've tried a number of different ideas I've found online too. I've tried both JavaScript and PHP solutions and all I can do is get the value but not set it. This is the code I have so far, which returns the drop down ID, I just need to know how to use it. I appreciate any help, thanks!
<?php
$pdo = new PDO('mysql:host=localhost; dbname=db', 'root', 'password')'
$sql = "SELECT divid, division FROM divisions ORDER BY division ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$divs = $stmt->fetchAll();
?>
<form method="post">
<select id="divi" name="divisions">
<?php foreach($divs as $div): ?>
<option value="<?= $div['divid'];?>"><?= $div['division']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['divisions'])){
$selected = $_POST['divisions'];
echo 'Selected: " . $selected;
} else {
echo 'Select division.';
}
}
?>
It's not very clear to me what you really want, however it looks like you want to select default:
<select id="divi" name="divisions">
<?php foreach($divs as $div): ?>
<option <?php echo ("mycondition ex: 'id == 1'") ? "selected" : NULL ?> value="<?= $div['divid'];?>"><?= $div['division']; ?></option>
<?php endforeach; ?>
</select>
You are simply missing any code that sets 'selected="selected"' in the HTML for the select field.
Also, your code is very hard to read so I've cleaned up the loop a little bit.
<form method="post">
<?php
echo '<select id="divid" name="divid">';
foreach ($divs as $div) {
$selected = '';
if (isset ($_POST['divid']) && ($_POST['divid'] == $div['divid'])) {
$selected = 'selected="selected"';
}
echo '<option value="' . $div['divid'] . '" ' . $selected . '>' . $div['division'] . '</option>';
}
echo '</select>';
Related
I have a drop down pull from an oracle database. when I select a drop down value and click a show details button , the details show but the drop down defaults back to the first one in the list. I need it to stay on the selected value.
I am doing this in PHP
I have tried this but it cannot recognize the
<form name= "fund" method="post" >
<label id= "fund" for="fund">Fund:</label>
<Select name="fund" id="fund">
<option value="--Select A Fund--">--Select a Fund--</option>
<?php
$sql = 'SELECT Account_name ||\' - \'|| Fund_id as FUND, FUND_ID FROM FUND_ACCOUNTS';
$stid = oci_parse($conn, $sql);
$success = oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
{
$selected = (!empty($_POST['fund']) && $_POST['fund'] == $row['FUND']) ? 'selected' : '';
echo '<option value="' . $row['FUND'] . '" ' . $selected . '>' . $row['FUND'] . '</option>';
}
?>
</select>
<input type="submit" name="fund"
value="Show Current Fund Investors"/>
</form>
<BR>
<?php
echo 1 . $row['FUND'];
echo 1 . $_POST['fund'];
?>
But $selected is never populated. Not sure where to go from here, and I am not a web developer. Any ideas where I am going wrong ?
the output of the final echos is 11Show Current Fund Investors
Likely this line just needs to do this:
$selected = (!empty($_POST['fund']) && $_POST['fund'] == $row['FUND'])) ? 'selected' : '';
What you have is matching the default option with || ($row['FUND'] == '--Select A Fund--') and probably also adding selected to the one you actually do select from the drop down. View the page source in the browser, there might be two options with the selected attribute.
By default, if nothing is selected, it will just show the first item in the dropdown which is --Select A Fund-- anyway.
Also you probably should have a space before the $selected variable and after the quote:
echo '<option value="' . $row['FUND'] . '" ' . $selected . '>' . $row['FUND'] . '</option>';
Should come out to:
<option value="whatever" selected>Whatever</option>
Edit
Based on your edit, you need to remove the name attribute from the submit button, or rename it. It’s conflicting with your select name.
<input type="submit" value="Show Current Fund Investors"/>
A tip:
You should encapsulate your fetching of that list in a function (at the very least) and include it in the page at the top:
/functions/fetchFundAccounts.php
<?php
function fetchFundAccounts($conn)
{
$stid = oci_parse($conn, 'SELECT Account_name ||\' - \'|| Fund_id as FUND, FUND_ID FROM FUND_ACCOUNTS');
$success = oci_execute($stid);
$results = [];
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {
$results[] = $row;
}
return $results;
}
To use:
<?php include(__DIR__.'/functions/fetchFundAccounts.php') ?>
<form name= "fund" method="post" >
<label id= "fund" for="fund">Fund:</label>
<select name="fund" id="fund">
<option value="--Select A Fund--">--Select a Fund--</option>
<?php foreach(fetchFundAccounts($conn) as $row): ?>
<option value="<?php echo $row['FUND'] ?>" <?php echo (!empty($_POST['fund']) && $_POST['fund'] == $row['FUND']) ? 'selected' : '' ?>><?php echo $row['FUND'] ?></option>
<?php endforeach ?>
</select>
<input type="submit" value="Show Current Fund Investors"/>
</form>
My drop down is showing blank then when i select the value of dropdown the same value is showing, but i have to show dropdown value as select first then when I click on button the respective value should show
I am doing a Php program
<form class="form-horizontal" name="form" method="post" action="<?php $_PHP_SELF?>">
<label for="courseDisp" class="col-sm-2" style="margin-top:10px;">Course : </label>
<?php
$course="SELECT * from course";
$res= $conn->query($course);
if($res->num_rows>0)
{
echo '<select name="courseDisp" id="courseDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0" selected> -- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["course_id"].'>'.$row['shortname'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<label for="yearDisp" class="col-sm-2" style="margin-top:10px;">Year : </label>
<?php
$year="SELECT distinct(year) from syllabus";
$res= $conn->query($year);
if($res->num_rows>0)
{
echo '<select name="yearDisp" id="yearDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0">-- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["year"].'>'.$row['year'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<script type="text/javascript">
document.getElementById('courseDisp').value = "<?php echo $_POST['courseDisp'];?>";
document.getElementById('yearDisp').value = "<?php echo $_POST['yearDisp'];?>";
<input type="submit" class="btn col-sm-2" style="margin-left:15px;margin-top:10px;width:60px;font-weight:bold;font-size:15px;" value="GO" name="btnGo" id="btnGo" />
</form>
I think you are doing it in a wrong way:
your code should look like this
<script type="text/JavaScript">
var valueSelected=document.getElementById('course').value;
alert(valueSelected);// do here according to the need
</script>
This is because there is no $_POST variables present before you submit a form.
$_POST variables can only be 'accessed' whenever a POST form is submitted, so when the form is not submitted, $_POST['course'] will be undefined. If you want to use persistant, but also relative variables, use $_GET.
This can be done the following way:
<script type="text/javascript">
document.getElementById('course').value =<?php echo $_GET['course'];?>";
</script>
(this will cause an error if value is not set, make sure to make exceptions for that, using if statements in PHP)
but the value also needs to be fetched from the URL.
so your url needs to have ?course=<course_value> in it, for example:
https://example.com/index.php?course=Course%201
Click here for more about POST vs GET requests
Instead of setting the value with javascript, you should directly write the selected attribute.
<select name="course">
<?php foreach ($options as $key => $value): ?>
<option value="<?= $key ?>"<?php if ($key == $_POST['course']) echo " selected" ?>>
<?= $value ?>
</option>
<?php endforeach; ?>
</select>
If you have to do this in javascript, keep sure, you use the correct syntax. Your example has a wrong " at the end of the line. Also you should use json_encode, if you want to output vars into javascript. And a last thing - if you don't put this inside the document ready event, the script has to be placed after the select element, which you wan't to manipulate
<select name="course">...</select>
...
<script type="text/javascript">
document.getElementById('course').value = <?= echo json_encode($_POST['course']) ?>;
</script>
Needed to keep the <option value="">-Select-</option>
If I generate a select list using PHP from the results of a database query, for some reason I can't then use Javascript to get the value of the currently selected item. I tested this code with a static list and it works no problem. Here is my code:
<?php
require_once("config.php");
$sql="SELECT * FROM animals ORDER BY name ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_UNIQUE); //each column is addressed by the primary key
}
catch (Exception $ex)
{
echo $ex->getMessage();
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#animal_list").change(function(){
var animalValue = $(this).val();
window.location.href="animal_list.php?id=" + animalValue;
});
});
</script>
</head>
<body>
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?>
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
</body>
</html>
Testing with a static list works. Here is the example:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="fruits.php?id=" + fruitValue;
});
});
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo 'My Fruit <input type="text" id="myfruit" value="' . $_GET['id'] . '" readonly>';
}
else
echo 'My Fruit <input type="text" id="myfruit" value="" readonly>';
?>
</body>
</html>
remove onchange="listChange()" because is not defined and we dont need it.
and use $(this).find('option:selected').val(); for get value of option selected.
$("#animal_list").change(function(){
var animalValue = $(this).find('option:selected').val();
window.location.href="animal_list.php?id=" + animalValue;
});
First off I would clean this mess up.
<select id="animal_list" name="animal_list">
<?php
foreach($results as $res)
{
?>
<?php echo '<option value="'. $res['id'] . '">' ?>
<?php echo $res['name'] ?> <!-- missing ; -->
</option>
<?php
}
?>
</select>
<br/><br/>
<?php
if(isset($_GET['id']))
{
echo '<input type="text" id="npsw_code" value="' . $_GET['id'] . '" readonly>';
}
else
echo '<input type="text" id="npsw_code" value="" readonly>';
?>
Sorry I just can't deal with poorly formatted code, it makes reading it a chore. It just seems like so much wasted effort.
<select id="animal_list" name="animal_list">
<?php foreach($results as $res): ?>
<option value="<?php echo $res['id'];?>"><?php echo $res['name']; ?></option>
<?php endforeach; ?>
</select>
<br/><br/>
<?php
$readonly = '';
$npsw_code = '';
if(isset($_GET['id'])){
$readonly = ' readonly';
$npsw_code = $_GET['id'];
}
?>
<input type="text" id="npsw_code" value="<?php echo $npsw_code; ?>" <?php echo $readonly; ?>>
We'll also ignore this (missing ; ):
<?php echo $res['name'] ?>
Probably a syntax error, but see that's what happens when you cant read the code.
Javascript don't care how the HTML got in the page, only what the HTML looks like. Without knowing what it looks like, all we can do is guess. You can view source and see what it looks like.
Otherwise, put an alert in the on change handler and see what it says.
$("#animal_list").change(function(){
var animalValue = $(this).val();
alert(animalValue);
window.location.href="animal_list.php?id=" + animalValue;
});
Alert has the nice side effect of halting/pausing Javascript execution so it will interrupt the page redirect. This will tell you 2 things,
your event is being fired on change
the value is correct.
Never mind it was a typo. The column in my database was 'code' not 'id'. So it should have read . Sorry for wasting your time.
i don't know how to explain well, but i want to display the name of the choice i made, and the names are in the database. To understand, here is my select :
<select name="options[1][]" id="perso_1" class="multiselect
required-entry product-custom-option" title=""
onchange="displayCondition()">
<option value="0" disabled>Testing</option>
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
Here is the function to display a message under the choice :
function displayCondition() {
condition = new Array("",
"<div class='bordure'><?php echo $row['perso_name']; ?></div>",
"<div class='bordure'><?php echo $row['perso_name']; ?></div>",
"<div class='bordure'></div>"
);
var getsel = document.getElementById('perso_1').value;
document.getElementById("divId").innerHTML = condition[getsel];
}
And the variables :
$getperso = "SELECT * FROM perso";
$persoresult = mysqli_query($connection, $getperso) or die("Erro!: " . mysql_error());
$row = mysqli_fetch_assoc($persoresult)
The code is working, but it only display the name of the first "perso_name" and i don't know how to change to the second one, maybe something like "perso_name(2)" or i don't know..
If you could help me, thanks a lot !
Add a while into your code without the while condition the query will only run once.Thats why it only display the name of the first person. Try do something like this
if(mysqli_num_rows(mysqli_query($getperso)) > 0)
{
$getperso = mysqli_query($getperso)or die(mysqli_error());
while($row = mysqli_fetch_assoc($getperso))
{
echo $row['perso_name'];
echo "</br>;
}
}
You can do it in by the following code :
<?php $getperso = "SELECT * FROM perso"; ?>
<select name="options[1][]" id="perso_1" class="multiselect
required-entry product-custom-option" title=""
onchange="displayCondition(this.value)">
<?php if(mysqli_num_rows(mysqli_query($getperso)) > 0)
{
$getperso = mysqli_query($getperso)or die(mysqli_error());
while($row = mysqli_fetch_assoc($getperso))
{ ?>
<option value="<?php echo $row['perso_name']; ?>"><?php echo $row['perso_name']; ?></option>
<?php }
} ?>
</select>
<script type="text/javascript">
function displayCondition(value) {
document.getElementById("divId").innerHTML = "<div class='bordure'>"+ value +"
</div>";
}
I think this might resolve your issue. All the best.
I want to hold selected value of drop down while submitting form on onchange event of drop down.
This is my code
echo "<form method=\"post\">
<select name=\"Color\" OnChange=\"this.form.submit();\"> ";
while($rec=mysql_fetch_array($query))
{
$value = $rec['name'];
echo "<option value=\"$value\">$value</option>";
if($row['name'] == $_SESSION['name'])
echo " selected";
}
echo "</select> "?>
You probably mean, if you submit the form but an error is on the inputs you want to keep the selected option.
Then, try this:
echo "<form method=\"post\">
<select name=\"Color\" OnChange=\"this.form.submit();\"> ";
while($rec=mysql_fetch_array($query)) {
$value = $rec['name'];
$selected = ( $value == $_SESSION['name'] ) ? ' selected' : '';
echo "<option value=\"$value\"$selected>$value</option>";
echo "</select> "?>
I however think that $_SESSION['name'] should be $_POST['name']
First of all, if($row['name'] == $_SESSION['name']) // instead of $row use $rec,because you used in mysql_fetch_array.
<form method="post">
<select name="Color" OnChange="this.form.submit();">
<?
while($rec=mysql_fetch_array($query))
{
$value = $rec['name'];
?>
<option value="<?echo $value;?>" <?if($rec['name']==$_SESSION['name']){echo "selected;"}?>>$value</option>
<?}?>
</select>
</form>