How can I retrieve selected value after form submision inside looped HTML select? I managed to solve the problem with manual if statements, but thats not dynamic.
I'm also storing previously submited value inside a cookie. I use self page form submit.
I managed to retrieve previous value from radio button:
<input type="radio" name="spol" value="moški" checked="checked" <?php if (isset($_POST['spol']) && $_POST['spol'] == 'moški') {
echo ' checked="checked"';
} ?>>
But can't find a way to do this inside foreach loop
<!---Cookie "keks" is storing previous submited string-->
<select name="status">
<?php
$_COOKIE['keks'];
$statusi = ["Dijak", "Študent", "Zaposlen", "Brezposelni"];
$counter= 0;
foreach ($statusi as $status) {
$counter++;
if ($counter == 2) {
echo "<option value=" . $status . " selected>" . $status . "</option>";
} else {
echo "<option value=" . $status . ">" . $status . "</option>";
}
}
?>
</select>
As stated in html comment, $_COOKIE['keks']; is storing the last value.
You might want to store that value into a variable or use it as is. and then, compare it against the current iteration of your loop.
$lastValue = $_COOKIE['keks'];
// some code
foreach ($statusi as $status)
{
if ($status == $lastValue)
// mark the option as selected
else
// don't mark it
}
Related
I have a wordpress site with a search form that searches for posts based on the form field selections, for custom fields etc. It works fine, however on the search results page I have an exact copy of the form except that I am trying to preset the form selections based on the search query/url string.
I am using a regular select dropdown and I have set it to "multiple" so that it can use bootstraps multiselect with the checkboxes. I've asked a similar question HERE but that was for checkboxes and even though the bootstrap multiselect uses checkboxes, I still have to work with the select dropdown first.
So after trying several things, I've come close but have ran into several problems. In the code below I made notes to further explain exactly what I mean.
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);
if ( $count > 0 ){
echo "<option value='Any'>All</option>";
foreach ( $terms as $term ) {
if (isset($_GET['property_type'])) {
foreach ($_GET['property_type'] as $proptypes) {
// FIRST EXAMPLE
$selected .= ($proptypes === $term->slug) ? "selected" : ""; // shows first correct selected value but also selects everything after it up until the second correct value, which it doesn't select.
//$selected = ($proptypes === $term->slug) ? "selected" : ""; // shows only last correct selected value
//if ($proptypes === $term->slug) { $selected = 'selected'; } // shows first correct selected value then selects every value after, even if it wasn't selected
// SECOND EXAMPLE
//$selected .= ($proptypes === $term->slug) ? "selected" : ""; // shows first correct selected value then selects every value after, even if it wasn't selected
//$selected = ($proptypes === $term->slug) ? "selected" : ""; // shows only last correct selected value
//if ($proptypes === $term->slug) { $selected = 'selected'; } // shows first correct selected value then selects every value after, even if it wasn't selected
}
}
echo "<option value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>"; // FIRST EXAMPLE
//echo "<option value='" . $term->slug . "' " . ($selected?' selected':'') . ">" . $term->name . "</option>"; // SECOND EXMAPLE
}
}
?>
</select>
Create and array and use in_array() to check.
<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms("property-type", array('hide_empty' => 0));
$count = count($terms);
// Setup an array of $proptypes
$proptypes = array();
if (isset($_GET['property_type'])) {
foreach ($_GET['property_type'] as $proptype) {
$proptypes[] = $proptype;
}
}
if ($count > 0) {
echo "<option value='Any'>All</option>";
foreach ($terms as $term) {
$selected = (in_array($term->slug, $proptypes)) ? 'selected' : '';
echo "<option value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>";
}
}
?>
</select>
I have a contact form inside a while loop, which will send an email to the user displayed in the while loop. But with this structure I would send an email to all objects inside the loop. I don't know how to escape the while loop in this case.
... while($row = $sql->fetchObject()){
... echo $row->userMail;
echo '<form ...><input name="contactMail"><...submit></form>';
if(isset($_POST['visitorMail']{
mail($toUserMail,$subject,$body_containsVisitorMail,$headers);
//this will send an email to all "objects" displayed in within the while loop -> problem
}
}
I suppose you need to check value of $_POST['contactMail'] with the current iterated one:
while($row = $sql->fetchObject()){
echo $row->mail;
echo '<form ...><input name="contactMail" value="' . $row->mail . '"><...submit>
<input type="hidden" name="itemId" value="' . $row->id . '"></form>';
if(isset($_POST['contactMail']) && $_POST['itemId'] == $row->id) {
mail($toRowMail,$subject,$body,$headers);
}
}
when i click the edit button it should go the edit page
when i want to edit the row with coursename="php" in the drop down the course name should have selected as php since the course name and the paper name,paper description are present in the different table i cant select the particular value in drop down
if(isset($_GET['id'])) {
$table="papers";
$condition="paper_id=".$_GET["id"]."";
$select=selectlist($table,$condition);
$row=$list->fetch_array();
$table="courses";
$datalist=selectdata($table);
$data=Selectdata($table);
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
}
}
?>
i have tried the above code i know the problem is with the "selected" please help me
You are almost close to the answer.
Some modifications and you are done.
You need to compare two values.
The value from database (selected value) and the value in loop.
Another suggestion is that we should not write any logic inside any
HTML tag.
HTMLs/Templates are just for printing output to screen.
We should first evaluate all conditions and then print HTML.
selected Reference
Change
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
To:
$selected = ($row1['course_id'] == $courseid) ? 'selected="selected"' : '';
echo '<option value="'. $row1['course_id'].'" ' . $selected . '>'.$row1['course_name'].'</option>';
Replace your while loop:
<?php
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
if($courseid == $row1['course_id']) {
echo '<option value="'. $row1['course_id'].'" selected>'.$row1['course_name'].'</option>';
} else {
echo '<option value="'. $row1['course_id'].'" >'.$row1['course_name'].'</option>';
}
}
?>
You can do it as following:
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
$selected="";
if($row['course_id']==$course_id)
{
$selected="selected";
}
echo '<option value="'. $row1['course_id'].'" $selected>'.$row1['course_name'].'</option>';
}
This makes your job done
while($row1=$result->fetch_assoc())
{
$coursename=$row1['course_name'];
$courseid=$row['course_id'];
$paper=$row['paper_name'];
$paperdesc=$row['paper_description'];
$_SESSION['pid']=$row['paper_id'];
echo "<option value = '{$row1['course_id']}'";
if ($courseid == $row1['course_id'])
echo "selected = 'selected'";
echo ">{$row1['course_name']}</option>";
}
Try this (use ternary operator inside option)
echo '<option value="'. $row1['course_id'].'" selected="'. $row1['course_id'].'=='.$courseid.'">'.$row1['course_name'].'</option>';
change into
<option value="<?= $row1['course_id'] ?>" <?= $row1['course_id']==$courseid? "selected":""?> > <?= $row1['course_name'] ?> </option>';
I have a country list of every country in a form to get a parcel quote.
When a user presses the "Get Quote" button, all the text forms retain the information previously entered using PHP.
How can I do this with the country list box? As I can't have PHP on every option checking if that is the country selected and adding "Selected" to the html.
Is there a better way other than generating the country list from a file in a loop?
EDIT:
Going for the method of looping through a file, and checking..
This is what I have so far:
$countries = fopen("includes/countries.txt", "r");
$countries = explode(";", $countries);
Then in the HTML:
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
echo("<option value=\"" . $country . "\">" . $country . "</option>");
}
?>
</select>
Not yet finished.
I assume you have an array with your countries stored. You could try something like this:
$countries = array('Albania', 'Egypt');
$selected_country_id = $_GET['c_id']; // You may need to change this to match with your code
$country_selected = array();
foreach($countries as $country) {
if($country['id'] == $selected_country_id) {
$country_selected[ $country['id'] ] = ' selected ';
} else {
$country_selected[ $country['id'] ] = '';
}
}
Then, assuming that you dynamically add your Select-Options, do this:
// In your each-fn
echo '<option value="' . $country['id'] . '" ' . $country_selected[ $country['id'] ] . '>' . $country['name'] . '</option>';
Something like this would be better
foreach ($countries as $country) {
?>
<option value="<?php echo $country" <?php echo ($country == $_POST['country'] ? 'selected' : ''; ?>><?php echo $country; ?></option>
<?php
}
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
if(isset($_POST["country"]) && $_POST["country"] == $country){
$sel = "selected";
}else { $sel= ""; }
echo("<option value=\"" . $country . "\"" .$sel.">" . $country . "</option>");
}
?>
</select>
Get All Country-State-City Selectbox ....!!!
See Link : GitHub
I have a select box that shows 3 options: option1, option2, option3. When a user hits submit, then in $_POST I do have the value selected. Is there an easy way to redisplay the select box with the chosen option highlighted WITHOUT it being repeated in the options?
In other words, if option2 is selected and submit is clicked, the page should display again with option2 selected, and option1 and option 3 underneath.
Thanks.
<?php
$arrValues = array(...);
$selectedValue = (isset ($_POST['selectName']) ? $_POST['selectName'] : "");
?>
<select name="selectName">
<?php
for ($i = 0; $i < count($arrValues); $i++)
{
$opts = ($arrValues[$i] == $selectedValue) ? ' selected="selected"': '';
echo '<option value="' . $arrValues[$i] . '"' . $opts . '>' . $arrValues[$i] . '</option>';
}
?>
</select>
Create your options like this.
$options = array("optionvalue" => "Option Name");
foreach($options as $value => $name)
{
if(isset($_POST['select_box']))
{
if($_POST['select_box'] == $value)
{
echo '<option selected="selected" value="'.$value.'">'.$name.'</option>';
continue;
}
}
echo '<option value="'.$value.'">'.$name.'</option>';
}
When you generate the select box, use the POST data (if available) to pick the item that's selected (and/or to sort the items).
Kind of like:
if($_POST["optval"] == $opt) $sel = "selected='selected'"; else $sel = "";
print "<option value='$opt' " . $sel . ">$opt</option>";
Naturally you'd want to verify that the POST data is valid and that it exists (isset). Assuming of course that you generate your select box from data accessible by PHP, rather than statically define it.