I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.
Related
I am using a form having select dropdown. I want to pass the value obtained from the selected option as a $_GET request in form action field but any ways to access it outside the foreach loop. Here is the code sample that I have written
<form id="dynamicForm" action="client-detail-dynamic.php?id=<?php echo $_GET['id']; ?>&r_id=<?php **PASS THE DROPDOWN VALUE ID HERE** ?>" method="post">
<select class="form-control" id="dynamicfy" name="dynamicfy">
<?php
$j = 0;
foreach($payment_data as $pd):
?>
<option value="<?php echo $payment_data[$j]->r_id; ?>"><?php echo $payment_data[$j]->fy; ?></option>
<?php $j++; endforeach; ?>
</select>
</td>
<td class="col-md-4">
<input type="submit" name="submit" id="submit" class="btn btn-sm btn-success">
</td>
</form>
NOTE: $payment_data is an array containing the table data with field names r_id, fy etc
I have two methods for this.
First method
Create a hidden field inside form element to store the value of id.Put form action null
<form id="dynamicForm" action="" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
On submit you will get two values
if(isset($_POST['submit'])){
$id=$_POST['id'];
$r_id=$_POST['dynamicfy'];
header("location: client-detail-dynamic.php?id=" . $id . "&r_id=" . $r_id . "");
exit();
}
Second method use javascript
<select class="form-control" id="dynamicfy" name="dynamicfy" onchange="rdrt(this.value)">
<script>
function rdrt(str){
id=<?php echo $_GET['id']; ?>;
if(str!=""){
location.href="client-detail-dynamic.php?id=" + id + "&r_id=" + str;
}
}
</script>
Rather than changing the page from FORM ACTION what you can do is pick the values and set them in url passed to header:location.
try this.
``<?php
if(isset($_POST['submit'])
{
$option = $_POST['dynamicfy'];
$id = $_POST['id']
header('location: http://client-detail-dynamic.php?id=$id,r_id=$option');
}
?>
<form id="dynamicForm" action="" method="post">
<select class="form-control" id="dynamicfy" name="dynamicfy">
<?php
$j = 0;
foreach($payment_data as $pd):
?>
<option value="<?php echo $payment_data[$j]->r_id; ?>"><?php echo $payment_data[$j]->fy; ?></option>
<?php $j++; endforeach; ?>
</select>
</td>
<td class="col-md-4">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<input type="submit" name="submit" id="submit" class="btn btn-sm btn-success">
" />
</td>
</form>
What you are trying to do is go somewhere based in the $_GET['id]. That's not possible server side as you have to FIRST make the request, then execute code. If your aren't trying to bring form data with you to this URL, then try this suggestion. However forget what I about not possible. you could do something like:
<?php
if(isset($_POST['submit-button'])) {
header("location: file.php?something=" . $_GET['id']);
}
// set the form action to nothing and add this to the same page the form is on
// and you can redirect based on the $_GET['id']
?>
To change value on selection of dropdown, You will need to use a jQuery on change of select box.
Please refer following code for same.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(Document).ready(function() {
jQuery('#dynamicfy').change();
});
jQuery('#dynamicfy').change(function() {
jQuery('#dynamicForm').attr('action', 'client-detail-dynamic.php?id=' +<?php echo $_GET['id']; ?> + '&r_id=' + jQuery(this).val());
});
</script>
if you just want selected dropdown on the action page then You may also get selected dropdown on the action page with using $_POST['dynamicfy'] on action page "client-detail-dynamic.php"
I have an an html form with only <select> element. Below the form I have a text box, I want to update the value of the text box based on the option selected in the form.
I am not sure if this is possible in PHP, I know I can do it with Javascript/Jquery, but I am working on a school project and its a PHP project. My teacher has done it but Im not sure if he used PHP.
Here is my code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = $_POST['books'];
echo "<input type='text' value='$choice'>";
?>
When the page first loads I want the value from the selected option to be in the text box. I am not sure how I could go about doing this in PHP. Help would be appreciated.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="javascript:document.form.submit();">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = isset($_POST['books'])?$_POST['books']:'';
echo "<input type='text' value='$choice'>";
?>
Edit, as a pure PHP solution with a submit button, which will load data on initial page load then load data with the submit button as per selection.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
echo "<input type='text' value='$choice'>";
}
else{
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
echo "<input type='text' value='$choice'>";
}
?>
Original answer with onchange
The following would work, using Javascript and getElementById which would echo the selection in a text box using an onchange function.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="update_textbox()" id="id_books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = isset($_POST['books']) ? $_POST['books'] : '';
echo "<input type='text' value='$choice' id='showit'>";
?>
<script>
function update_textbox(){
var selectbox = document.getElementById('id_books');
var id_books = selectbox[selectbox.selectedIndex].text;
document.getElementById('showit').value=id_books ;
}
</script>
To load data into the text box at initial page load, use:
Replace:
$choice = isset($_POST['books']) ? $_POST['books'] : '';
with:
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
When you first load the page, there are no POST data, so you could set $choice to the first book in list:
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
But you have to udnerstand the difference between PHP and JavaScript in here.
PHP can only change the value, when there is a request on the server as it is a server-side language. If you wish to update the value instantly, without submiting the form, you need to use JavaScript.
if it must be purely PHP, then put a submit button on your form for when a selection is made. This will set the value you are looking for. Others have provided samples on how to do this form submission automatically with javascript, but the end result is the same.
You can do it with PHP, it looks as though you're just missing the submit button to actually post the selection.
To submit the form without a submit button, you need to use javascript, eg.
<select onchange="this.form.submit()">....</select>
Below is a simple example (static options rather than xml) that also sets the selected option in the select (IMO this is a more practical use than printing it in the text input)
<?php
$val = isset($_REQUEST['books']) ? $_REQUEST['books'] : null;
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="this.form.submit()">
<option value=>Choose a book</option>
<option<?php if($val && $val === 'opt 1'){ print ' selected';}?>>opt 1</option>
<option<?php if($val && $val === 'opt 2'){ print ' selected';}?>>opt 2</option>
</select>
<noscript><button type="submit">Submit</button></noscript>
</form>
<?php if($val){ ?>
<input type="text" value="<?php echo $_REQUEST['books']; ?>">
<?php } ?>
This is probably ok just for a school exercise, but in the real world you would probably want to sanitize any user input ($_REQUEST['book'] / $_POST['book']) and use a better templating engine than vanilla PHP (I like Twig) to help separate presentation from functional logic.
I've been working on a PHP form that changes values in a file on my server. The form changes the values correctly but I need the <option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option> part of the form to always show to current value that is set in the file, currently it does not.
#file contents (the lines the values are on changed on a regular basis)
size=large
color-name=red
shape=round
height=short
weight=heavy
<?php
$file = "/home/user/color.props";
$contents = file($file, FILE_SKIP_EMPTY_LINES);
foreach($contents as $line) {
list($option, $value) = explode('=', $line);
if ($option == 'color-name') {
$color_name = $value;
} elseif ($option == 'shape') {
$shape = $value;
}
}
if(isset($_REQUEST['color_choice'])){
exec('sed -i '.escapeshellarg('s/color-name=.*/color-name='.$_REQUEST['color_choice'].'/g')." /home/user/color.props");
echo 'Color setting has been updated';
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="color_choice">;
<option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option>;
<option value="square" <?php if($shape == 'square'){?>selected="selected"<?php }?>>Square</option>;
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
I'm still unclear on what exactly you're trying to accomplish. Your current code is only saving the last 'color-name' and 'shape' objects being read in from the file. It then can configure the selected option by making this change:
<option value="red" <?php if($color_name == 'red'){?>selected="selected"<?php }?>>Red</option>;
<option value="blue" <?php if($color_name == 'blue'){?>selected="selected"<?php }?>>Blue</option>;
<option value="green" <?php if($color_name == 'green'){?>selected="selected"<?php }?>>Green</option>;
<option value="purple" <?php if($color_name == 'purple'){?>selected="selected"<?php }?>>Purple</option>;
NOTE: The way you're reading in the file appends carriage returns/line returns at the end of your variables...for example, $color_name on my end contains two extra hex values at the end of the string: x0d and x0a
EDIT #2: Try making your form like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id="color_choice">
<option id="round">Round</option>
<option id="square">Square</option>
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
<script>
var option = document.getElementById("color_choice");
option.options['<?php echo $shape ?>'].selected = true;
</script>
I'm pretty sure this will work, changes I made were:
1) Using javascript instead of php to change selected
2) Using id attributes instead of value or name
3) Added <script> tag at the end of form (it may not work if it's before)
You'll have to make changes to the form and the script depending on what type of values you're pulling from the file...but you should be able to figure out how to handle that.
I need to pass a few GET variables through. The link I need is
index.php?type=door&qty=4
I can write this easily enough like
But I need to select the $qty amount fron a drop down list. So I have
<form name="qty" method="GET" action="../../../index.php?door-type="<?php echo $door_model; ?>">';
<select>
<?php
for ($front_int=1; $front_int<=99; $front_int++)
{
echo'<option value="'.$front_int.'">'. $front_int . '</option>';
}
?>
</select>
<input type="submit" value="front-qty">
</form>
So how can I append these two values into one so that I get then $_GET them on the next page like I would with that first link I created?
If qty needs to be a select, then give that name to the select. Also, pass the other variable with a hidden field, which is pretty standard. Good luck :)
<form name="NOT_QTY" method="GET" action="../../../index.php">
<input type="hidden" name="door-type" value="<?php echo $door_model;?">
<select name="qty">
<?php
for ($front_int=1; $front_int<=99; $front_int++)
{
echo'<option value="'.$front_int.'">'. $front_int . '</option>';
}
?>
</select>
<input type="submit" value="front-qty">
</form>
I have this PHP code:
$result = mysql_query("SELECT distinct om_quote_no from `porders` order by om_quote_no desc") or die(mysql_error());
echo '<select name="project_no">';
while ($row = mysql_fetch_array($result)) {
echo "<option value=".$row['om_quote_no'].">".$row['om_quote_no']."</option>";
}
echo '</select>';
?>
<input type="submit" value="Submit" />
</form>
<div id="table">
<?php
if($_GET){
So as you can see the PHP is forming a dropdown input and once submitted its going to execute some code, but what i need to do is have two dropdown inputs and therefore two submit buttons, however i'm not sure how to form the PHP if statement to distinguish which submit was pressed, so i'll have(pseudo):
if (submit1){
}
if (submit2){
}
Is that possible?
If you give your <input type="submit"> elements names, the one that is clicked will have its name and value sent to the server.
<input type="submit" value="Submit" name="submit1">
if clicked will send submit1=Submit to the server. You could therefore check with if ($_GET['submit1']) to see if it was pressed.
This isn't the best way but can do something like this too:
<select name="test" onchange="document.location ='test.php?submit=dropdown1'">
<option>test</option>
<option>test1</option>
</select>
<br><br>
<select name="test1" onchange="document.location ='test.php?submit=dropdown2'">
<option>test2</option>
<option>test3</option>
</select>
within test.php file:
if($_GET['submit'] == 'dropdown1')
{
print "One";
//statements to execute
}elseif($_GET['submit'] == 'dropdown2'){
//statements here to execute
print "Two";
}
<input type="submit" value="Submit 1" name="submit1"/>
<input type="submit" value="Submit 2" name="submit2"/>
<?php
if(isset($_POST['submit1'])){
//do stuff
//grab select option
$select_option=$_POST['project_no'];
}else if(isset($_POST['submit2'])){
//do stuff
}else{
//do stuff
}
?>
Or if your method is GET than change $_POST to $_GET :)