Iam trying to make a dropdown select "sticky", basically I need to retain the value of the dropdown select in a session variable, then use the session variable in the doprdown select, so that when the page is refreshed, the value is retained in the dropdown select. I am trying to do this in php.
Here is the code for the select :
<?php
$countryId = isset($_POST['country']) ? $_POST['country'] : '';
asort($dirs);
reset($dirs);
echo '<option value="" disabled selected>Select Your Country</option>';
foreach ($dirs as $p => $w):
$selected = $countryId === $w ? 'selected' : '';
echo '<option value="' . $w . '" ' . $selected . '>' . $w . '</option>';
endforeach;
?>
Any advice is greatly appreciated
make a second file called savesession.php
<?php
if (isset($_GET['country_option'])) $_SESSION['country_option'] = $_GET['country_option'];
then change your code to be
<?php
$countryId = isset($_POST['country']) ? $_POST['country'] : isset($_SESSION['country_option']) ? $_SESSION['country_option'] : '';
asort($dirs);
reset($dirs);
echo '<option value="" disabled selected>Select Your Country</option>';
foreach($dirs as $p => $w):
$selected = $countryId===$w ? 'selected' : '';
echo '<option value="'.$w.'" '.$selected.'>'.$w.'</option>';
endforeach;
?>
<script>
function onDropDownChange(){
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
var ajax = new XMLHttpRequest();
ajax.open("GET", "yourpage.com/savesession.php?country_option=" + selectedItem, true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
}
}
}
</script>
then add an onchange="onDropDownChange" and id="dropdownID" to the <select> so that it calls a javascript function onDropDownChange
Related
How will i set the selected item in select2 multiple ? i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
<?php
$mytitle = array(
"867310020292434, 867310021548131, 867310021561670");
$test = implode(',', $mytitle);
$query=mysqli_query($link,"select * from inventory where ITEM_CODE_MX='OPP01-3006GRY'");
while($row=mysqli_fetch_array($query))
{
$imei=$row["IMEI_MX"];
$title = explode(',', $imei);
}
?>
<script>
$(function () {
$('#tags').select2();
function select (event){
$("#tags").select2({
maximumSelectionLength: $('#quantitytotransfer').val(),
formatSelectionTooBig: function (limit) {
$('#box').show().text('Callback!');
parseInt($("#quantitytotransfer").val())
return 'Too many selected elements (' + limit + ')';
}
});
}
$('#quantitytotransfer').on('keyup', select);
select()
});
</script>
<select id="tags" name='title[]' style="width:300px;" class="form-control select2-offscreen" onchange="getCount()" multiple>
<?php
foreach ($title as $opt) {
$sel = '';
$wew = trim($is);
if (in_array($opt, $mytitle)) {
$sel = 'selected="selected" ';
}
if (!empty($opt)) {
echo "<option ' . $sel . ' value='$opt'>$opt</option>";
}
}
?>
</select>
if you want to select the first option here is the code
$sel = "selected";
foreach ($title as $opt) {
if (!empty($opt)) {
echo "<option value='" . $opt . "'" . $sel . ">" . $opt . "</option>";
$sel = "";
}
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've a table with multiple rows, each row has a drop down list. I am new to javascript and is unable to retrieve the selected value from the row. Any idea how can it be done? Thanks in advance.
Code:
function chng_page(serialNum, rowid)
{
alert(rowid);
alert(serialNum);
var select_index = document.getElementById('orderStatus').selectedIndex;
//get the value of selected option
var option_value = document.getElementById('orderStatus').options[select_index].value;
//redirect with value as a url parameter
window.location = 'orderStatus.php?serialNum=' + serialNum + '&status=' + option_value;
}
</script>
//code for drop down list
<select id="orderStatus" name="orderStatus" onchange="chng_page(<?php echo $serialNum? >, this.parentNode.parentNode.rowIndex)">
<option value="Pending" <?php echo ($status == "Pending") ? ' selected="selected"' : ''; ?>>Pending</option>
<option value="Cooking" <?php echo ($status == "Cooking") ? ' selected="selected"' : ''; ?>>Cooking</option>
<option value="On The Way" <?php echo ($status == "On The Way") ? ' selected="selected"' : ''; ?>>On The Way</option>
<option value="Delivered" <?php echo ($status == "Delivered") ? ' selected="selected"' : ''; ?>>Delivered</option>
</select>
You didn't mention if the select element in each row has a unique id or not, but it somehow shows in your code that they do.
In that case, you can use JQuery (a popular JavaScript framework) to retrieve the selected value.
Assuming you have included the JQuery file in your HTML, and attached an event handler to the select element (to make it easier, pass in the id of the current select element as a parameter in the function), do this:
var selected_value = $("#id_of_select_element option:selected").val();
If the ids of the select elements are unique, that single line of code will definitely work.
You have the same name/id for the drop down in all table rows
If there is a dropdownlist in each row with same id-> #orderStatus, you should try this,
function chng_page(serialNum, ddlist)
{
var rowid = ddlist.parentNode.parentNode.rowIndex
alert(rowid);
alert(serialNum);
var select_index = ddlist.selectedIndex;
//get the value of selected option
var option_value = ddlist.options[select_index].value;
//redirect with value as a url parameter
window.location = 'orderStatus.php?serialNum=' + serialNum + '&status=' + option_value;
}
<select name="orderStatus" onchange="chng_page(<?php echo $serialNum?>, this)">
<option value="Pending" <?php echo ($status == "Pending") ? ' selected="selected"' : ''; ?>>Pending</option>
<option value="Cooking" <?php echo ($status == "Cooking") ? ' selected="selected"' : ''; ?>>Cooking</option>
<option value="On The Way" <?php echo ($status == "On The Way") ? ' selected="selected"' : ''; ?>>On The Way</option>
<option value="Delivered" <?php echo ($status == "Delivered") ? ' selected="selected"' : ''; ?>>Delivered</option>
</select>
I have a dropdown menu populated from a table in a MySQL database. It functions, but I would like to add an if/else statement to the code to change the default value of the dropdown according to the conditions.
Here is the code for the dropdown (much thanks to AlienWebguy for his assistance in getting this far):
<?php
$sql="SELECT techID, tech_userlogin FROM technicians";
$result=mysql_query($sql);
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech_userlogin=$row['tech_userlogin'];
// Here - check if the $_GET value in the query matches the tech_userlogin
($selected = ($tech_userlogin == $_GET['wtech_userlogin']) ? 'selected="selected"' : '');
echo '<option value="' . $tech_userlogin . '" ' . $selected . '>' . $tech_userlogin . '</option>' . "\n";
}
?>
I've tried a couple of things to accomplish what I'm after, but I'm severely hampered by my lack of experience and/or expertise in PHP/MySQL.
This is the first time I've tried these things and it has been hit and miss so far. I've recieved help here at Stack Overflow and I'm grateful such a resource exists.
This is my latest effort and it fails to achieve what I'm after. I want the default value of the dropdown to be "--Select Technician--" if the condition is not met in the if statement.
<?php
$sql="SELECT techID, tech_userlogin FROM technicians";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech=$row['tech_userlogin'];
$options.="<option value=\"$tech\">$tech</option>";
// Here - check if the $_GET value in the query matches the tech_userlogin
if
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
{echo '<option value="' . $tech . '" ' . $selected . '>' . $tech . '</option>' . "\n";}
else
{echo '<option value="' . $options . '" . 'selected="selected"'>'--Select Tech--'<. $options .>' . "\n";}
}
?>
Can someone please help me or point me in the right direction? Many thanks.
Cheers
Try this
<select name="whatever">
<option value="">-- Select Technician --</option>
<?php while ($row = mysql_fetch_array($result)) :
$techId = $row['techID']; // why isn't this used?
$tech = htmlspecialchars($row['tech_userlogin']);
$selected = $row['tech_userlogin'] == $_GET['wtech_userlogin'] ? '" selected="selected' : '';
?>
<option value="<?php echo $tech, $selected ?>"><?php echo $tech ?></option>
<?php endwhile ?>
</select>
If the whole if/then is just there to create a default, you're making it way too complicated.
$options = '<option value="">--Select Tech--</option>';
while ($row=mysql_fetch_array($result))
{
$techID = $row['techID'];
$tech = $row['tech_userlogin'];
$selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '';
$options .= '<option value="' . $techID . '" ' . $selected . '>' . $tech . '</option>' . "\n";
}
Now $options has all of your options in it, including a default option (--Select Tech--, with empty value) that shows up first, and will therefore start out selected if nothing else has the selected attribute.
Note that you also had $tech in the value of your option, but I assumed you meant to say $techID.
You wrote this, which isn't doing what you want:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
Change to this:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : false)
Notice the 'false'. You need that because empty quotes is not false, it is considered 'true' by PHP.
I could be wrong, but I believe the problem is with your if statement. You have:
($selected = ($tech == $_GET['wtech_userlogin']) ? 'selected="selected"' : '')
The problem is that you are assigning the result of the ternary statement to the variable $selected, which will always return a true for a successful assignment.
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.