retaining drop down value after submit in PHP - javascript

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>

Related

PHP set dropdown value after page refresh

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>';

how to retain drop down values as the value selected after submit

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>

Display the name of the value in my database for each option

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.

How Add select box Dynamically, which retrieve data from Database

I have problem with Web Development,
i have added drop down list using PHP, MySQL and HTML. Now i want to use button and dynamically generate same Select box again and again. How can i do this, please help me..
Here is my Select Box Code.
<Select name="txt-computer_sn" class="form-control" id="txt-computer_sn">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
if the data of dropdown will remain same then you can do that in this way
html and php
<Select name="txt-computer_sn" class="form-control dynm_drop" id="txt-computer_sn">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
jquery
$("#buttonid").click(function(){
$(".dynm_drop").clone().appendTo("class or id of element");
});
Try this:
<div class="select_wrapper">
<select name="txt-computer_sn[0]" class="form-control" id="txt-computer_sn_0">
<?php
include ('../svr/connection.php');
$sql = "SELECT * FROM supplier";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<option value=' . $row['supplier_id'] . '>' . $row['supplier_name'] . '</option>';
}
?>
</select>
<input type="button" name="add_select" class="add_select" value="Add New">
</div>
<script type="text/javascript">
$(document).ready(function() {
var s=1;
$('.add_select').click(function(e){ //Once add button is clicked
e.preventDefault();
s++;
$('.select_wrapper').append('<select class="form-control" name="txt-computer_sn['+s+']" id="txt-computer_sn_'+s+'">'+$('#txt-computer_sn_0').html()+'</select>');
});
});
</script>
there is 3 method to do this.i am not familiar with php.but i tell the method how to work it out.
1.you have to set an hidden field for count
2.
<select class="form-control" name="txt-computer_sn--" id="txt-computer_sn_--">
3.in the script write this var rep=/--/gi;
4. take your count from hidden field
var Count= $("#Count").val()
Count =++Count
("#div1").append($("#div2").html().replace(rep,Count));
on click the add button you have append the div2 with select to another
div1
on remove the
$("#div3"+id).remove()
in the order
<div1></div>
<div2 id="name1--"style=display:none>
<div3 id="name2--"></div3>
</div2>
it will work.use this concept .you can do this in php also..

Hold selected item in Drop Down php

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>

Categories