I have an option menu as follows:
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php
do {
?>
<option value="<?php echo $row_Recordset2['Cycle'] ?>"
<?php
if ($varCycle_DetailRS4 == $row_Recordset2['Cycle']) {
echo 'selected';
} elseif ($varCycle2_DetailRS4 == $row_Recordset2['Cycle']) {
echo 'selected';
} else {
echo '';
}
?>
>
<?php echo $row_Recordset2['Cycle'] ?>
</option>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
?>
</select>
Currently, the default selection is showing all records. I would like for the default to be the latest set of data equal to:
<?php echo $row_RecordsetCycle['Cycle']; ?>
So option menu would list 1,2,3,4,5 with 5 being the default when the page loads. User can then pick any option available. is set to last record in table with a limit of 1 so it will always echo the last record, which composes the option menu.
Help please. What should I edit so that the one record in
<?php echo $row_RecordsetCycle['Cycle']; ?>
is the default or selected option menu when the page loads? Currently, the default just shows all records and is extremely slow to load, hence why I want the latest record to be the default.
I took a stab at rewriting this. (code at the end)
the first thing I did was turn your do_while loop into a while loop as I think it was adding unnecessary confusion to the code
after doing that I moved some code
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
above the while loop as I thought it was needed to "prime the pump" of the while loop
I also pulled the
if ($varCycle_DetailRS4 == $row_Recordset2['Cycle']) {
return ' selected';
} elseif ($varCycle2_DetailRS4 == $row_Recordset2['Cycle']) {
return ' selected';
} else {
return '';
}
out into a function so as to simplify the code further
now here come my assumptions I assumed that $varCycle_DetailRS4 was the last value and that $varCycle2_DetailRS4 was the currentlySelected that was set befor the code provided;
if that is the case and that $varCycle2_DetailRS4 would be unset if it was the first then all that would need to be done is to slightly modify the isSelected to only set one option as selected.
<?php
function isSelect($value)
{
$lastValue = $varCycle_DetailRS4;
$currentlySelected = $varCycle2_DetailRS4;
if(isset($currentlySelected))
{
$selectValue = $currentlySelected;
}
else
{
$selectValue = $lastValue;
}
if ($selectValue == $value) {
return ' selected';
} else {
return '';
}
}
?>
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php
$rows = mysql_num_rows($Recordset2);
if ($rows > 0) {
mysql_data_seek($Recordset2, 0);
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
}
while ($row_Recordset2 = mysql_fetch_assoc($Recordset2))
{
$value = $row_Recordset2['Cycle']
echo " <option value=\"".$value."\"".isSelect($value).">".$value."</option>/n";
} ;
?>
</select>
Try using end() to get the last array:
<?php
$arr =array(1,2,3,4,5);
$last = end($arr);
?>
<select name="selCycle" id="selCycle" onChange="formFilter.submit()">
<option value="%">all cycles</option>
<?php foreach($arr as $key=>$val):
if(in_array("$last", array($val))==true){
echo '<option value="" selected="selected">'.$val.'</option>';
continue;
}
echo '<option>'.$val.'</option>';
endforeach; ?>
</select>
Stop using mysql extension, use pdo or mysqli. Using your question code, it should be:
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$last = end($row_Recordset2);
foreach($row_Recordset2 as $key=>$val){
//other code
if(in_array("$last", array($val))==true){
echo '<option value="" selected="selected">'.$val.'</option>';
continue;
}
echo '<option>'.$val.'</option>'
}
Working Demo
Related
I use bootstrap selectpicker to select multiple options.
Code is:
<select id="product_parent_id" class="selectpicker" size="1" name="product_parent_id[]" multiple data-selected-text-format="count">
<?php
foreach ($result_cat as $key => $cat) {
$cat_name='';
if($cat->category_parent_id!=0) {
$cnt=0;
$cat_name='';
$r_cat=$cat->category_parent_id;
do {
$cnt++;
$qur='SELECT category_parent_id FROM #__virtuemart_category_categories WHERE id='.$r_cat;
$db->setQuery($qur);
$r_cat=$db->loadResult();
} while($r_cat!=0);
for($i=0;$i<$cnt;$i++) {
$cat_name=$cat_name.'-';
}
$cat_name=$cat_name.$cat->category_name;
} else {
$cat_name=$cat->category_name;
}
$sel_c='';
if(in_array((string)$cat->id,$sel_cat_arr)) {
$sel_c='selected="true"';
}
?>
<option value="<?php echo $cat->id;?>" <?php echo $sel_c;?>><?php echo $cat_name;?></option>
<?php
}
?>
</select>
I downloaded bootstrap-selectpicker.zip
I use cdn: bootstrap-select.css,bootstrap-select.js
The selectpicker works in normal html page but in joomla select box it is not displayed. I found conflicts, but didn't get the solution.
Check if this works,
<?php
foreach ($result_cat as $key => $cat) {
$cat_name='';
if($cat->category_parent_id!=0)
{
$cnt=0;
$cat_name='';
$r_cat=$cat->category_parent_id;
do{
$cnt++;
$qur='SELECT category_parent_id FROM #__virtuemart_category_categories WHERE id='.$r_cat;
$db->setQuery($qur);
$r_cat=$db->loadResult();
}while($r_cat!=0);
for($i=0;$i<$cnt;$i++)
{
$cat_name=$cat_name.'-';
}
$cat_name=$cat_name.$cat->category_name;
}
else
{
$cat_name=$cat->category_name;
}
$sel_c='';
if(in_array((string)$cat->id,$sel_cat_arr))
{
$sel_c='selected="true"';
}
echo '<option value=\"'.$cat->id.'">'.$cat_name.'</option>';
?>
I'd like to add "selected" attribute to a combo box. This is my PHP:
if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }
if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }
if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }
if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }
I may have over hundreds of IF's.
I've tried this one, but It seems not working:
for($a=1; $a<=4; $a++){
if($results['status'] == $a)
{ $ok = "selected"; }
else
{ $ok = ""; }
}
I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way
Edit (My combo box):
<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>
Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!
// initialize all 4 to blank
for($a=1; $a<=4; $a++){
${"ok" . $a} = "";
}
// set the one that is selected
${"ok" . $results['status']} = "selected";
This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.
You can do this way,
<?php
// status list array
$selectValues = array(1, 2, 3, 4);
echo '<select name="combo_name">';
foreach($selectValues as $value){
$selected = "";
if($results['status'] == $value){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';
?>
All you have to do is make an array and loop through it-
<?php
$results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`
$arr = array("1" => "A",
"2" => "B",
"3" => "C",
"4" => "D"
);
?>
<select>
<?php
foreach($arr as $key => $val){
$sel = ($results_status == $key) ? "selected='selected'" : "";
?>
<option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>
You need to check every time for the selected value in the combo box.
Hope this helps
$combolength - the number of options in combo
$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
case $results['status']:
$ok[$results['status']]= 'selected';
break;
}
I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable, especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:
/core/classes/Form.php
class Form
{
# The idea here is that you would have many methods to build form fields
# You can edit this as you please
public function select($settings)
{
$class = (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
$selected = (!empty($settings['selected']))? $settings['selected']:false;
$other = (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
ob_start();
?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
<?php foreach($settings['options'] as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
To use:
# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
'name'=>'status',
'class'=>'classes here',
'id'=>'select1',
'other'=>array(
'data-instructions=\'{"stuff":["things"]}\'',
'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
),
# Options can be assign database returned arrays
'options'=>array(
'_'=>'Select',
1=>'A',
2=>'B',
3=>'C',
4=>'D'
),
'selected'=>((!empty($results['status']))? $results['status'] : '_')
));
Gives you:
<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
<option value="_">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
HTML:
<select name="taskOption[]" multiple>
<option>first<br /></option>
<option>second<br /></option>
<option>third</ option>
</select>
PHP:
<?php
foreach ($_GET['taskOption'] as $selectedOption){
echo "lesson:".$selectedOption."<br>";}
?>
This php code simply prints the selected options.
How can i separately do something if an option is selected ? for example
if (taskOption[0] is selected){
$x="1";
if (taskOption[1] is selected){
$y="1";
What i have tried with partial success so far is this:
$options = array("", "", "");
foreach ($_GET['taskOption'] as $selectedOption)
echo "".$selectedOption."<br>";
if($selectedOption == 'first'){
$options[0] = "11";
echo $options[0];
}
elseif($selectedOption == 'second'){
$options[1] = "22";
echo $options[1];
}
elseif($selectedOption == 'third'){
$options[2] = "33";
echo $options[2];
}
but i still have problem when i choose 2+ option..
(it only echo the last option)
You should add values to the options in the select tag first, so you can easy identify each one.
<select name="taskOption[]" multiple>
<option value="one">first<br /></option>
<option value="two">second<br /></option>
<option value="three">third</ option>
</select>
After it, you should remove the "elseif" and simply do ifs for all
$options = array("", "", "");
foreach ($_GET['taskOption'] as $selectedOption)
echo "".$selectedOption."<br>";
if($selectedOption == 'one'){
$options[0] = "11";
echo $options[0];
}
if($selectedOption == 'two'){
$options[1] = "22";
echo $options[1];
}
if($selectedOption == 'three'){
$options[2] = "33";
echo $options[2];
}
Im mantaining your code but it can be improveed a lot. Im not sure why are you adding the values to an array ($options).
You should add the value attributes to your option elements
<option value="first">first<br /></option>
<option value="second">second<br /></option>
<option value="last">third</option>
You are not wrapping your logic inside of the foreach.
foreach ($_GET['taskOption'] as $selectedOption){
echo "selected: ".$selectedOption;
if($selectedOption === 'first'){
$options[0] = "11";
echo $options[0]."<br>";
}
elseif($selectedOption ==='second'){
$options[1] = "22";
echo $options[1]."<br>";
}
elseif($selectedOption ==='third'){
$options[2] = "33";
echo $options[2]."<br>";
}
echo"end";
}
You need to put the swirly brackets around your logic to make sure everything beneath runs.
I have a dropdown control which and I would like it to default to a specific option based on the access of the logged in user. For example, the dropdown has 10 options but only administrators have access to view all 10 options. The majority of users only have access to 1 of the options though. The page contents are hidden/displayed based on whether or not the value of the dropdown is null.
Question: Using the example above, if an admin is logged in I need the dropdown to default to "Select an option". This way the page content is hidden. On the other hand, if a user with access to only 1 is logged in, I need it to default to that 1. This way they don't have to select anything and, by default the page content is displayed. How do I go about doing this?
Below is my current code which handles what the dropdown displays based on when a selection is made.
PHP/HTML
// Hide/Show main content div
<?php
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) { // If value is null, default to 'Select an option'
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
while ($row = odbc_fetch_array($db)) {
echo "<option value=\"".$row['content']."\">".$row['content']."</option>";
}
} else { // If value not null keep the selected value selected
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
// Pass selected value on change
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
SQL
// Hardcoding user for testing purposes, THIS WILL BE CHANGED
function getOptions() {
$results = "SELECT content, userid FROM table WHERE userid = 'username'";
return $results;
}
Any help is much appreciated and please let me know if I'm not clear about anything.
Got some help and have it figured out now. Here is the revised code:
PHP/HTML
// Hide/Show main content div
<?php
$src = null;
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) {
$i = 0;
$content = "";
while ($row = odbc_fetch_array($db)) {
$content .= "<option value=\"".$row['content']."\">".$row['content']."</option>";
$i++;
}
if ($i > 1) {
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
}
echo $content;
if ($i > 1) { $oneopt = 1; }
else { $oneopt = 0; }
} else {
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
<?php
global $optone;
if ($optone == 1) {
echo "$('#select1').trigger('change');";
}
?>
SQL -- Stays the same
#chenasraf really appreciate the help! Hope this can be of some help to someone in the future!
The preselected option is always the first to have a "selected" attribute. Your first disabled one has it first on all cases, so it's always chosen. Remove that and work from there.
On a side note, I think you can manage to make this options part work better. I've taken the liberty of rewriting it for you:
<select name="select1" id="select1">
<?php
$selected = '';
while ($row = obdc_fetch_array($db)) {
$options[] = '<option value="'.$row['content'].'">'.$row['content'].'</option>';
if ($row['content'] == $src)
$selected = count($options) - 1;
}
array_unshift($options, '<option disabled="disabled"', $selected == '' ? ' selected="selected"' : '','>--Select an option--</option>');
foreach ($options as $option) {
echo $option;
}
?>
</select>
I am still a beginner with PHP. I am having a problem with drop downs and links. I want to be able to choose an option in the drop down menu and it go to the specified page. For some reason only the links for the second drop down menu. (MUNICIPALITIES) will work correctly by linking to the specific municipality page. The crime drop down menu will not link to the specific crime page. I have included the code for the crime drop down and municipality drop down. I have also included the script below.
Ultimately my question is why aren't both drop downs functioning correctly with the link?
<script language="JavaScript" type="text/javascript">
function gopage(theLink) {
if (document.dropdown.theLink.value != "") {
location.href = document.dropdown.theLink.value;
}
}
</script>
<form name="dropdown">
<select name="theLink" onchange="gopage(theLink)">
<option value="ALL">Choose Crime associated with the Gang</option>
<?php
//echo 'NOWWWWWWWWWWWWWWWWWWWWWW';
if ($length3 <> 0) {
for ($m = 0; $m < $length3; $m++) {
$rows = $resultset3[$m][crime_name];
$trackchoices = $rows;
$options2 = "<option value=\"crimesmain.php?crime=$trackchoices\">$trackchoices</option>";
echo "$options2";
}
}
else if ($length3 == 0) {
$trackanswer = "NO CRIMES";
$options5 = "<option value=\"$trackanswer\">$trackanswer</option>";
echo "$options5";
}
?>
</select>
</form>
<br>
<br>
<form name="dropdown">
<select name="theLink" onchange="gopage(this)">
<option value="ALL">Choose Municipality associated with the Gang</option>
<?php
if ($length12 <> 0) {
for ($q = 0; $q < $length12; $q++) {
$rows2 = $resultset6[$q][municipality_name];
$trackchoices2 = $rows2;
//try
$options3 = "<option value=\"municipalitymain.php?mun=$trackchoices2\">$trackchoices2</option>";
//echo "<a href='municipalitymain.php?mun=$options3'>";
echo "$options3";
}
}
else if ($length12 == 0) {
$trackanswer = "NO MUNICIPALITY";
$options6 = "<option value=\"$trackanswer\">$trackanswer</option>";
echo "$options6";
}
?>
</select>
</form>
I think a better solution would be to pass the id of the select element to gopage so your function looks like this
function gopage(elId)
{
if (document.getElementById(elId).value != "") {
location.href = document.getElementById(elId).value;
}
}
First Dropdown
<select name="theLink" id="crime" onchange="gopage('crime')">
Second Dropdown
<select name="theLink2" id="muni" onchange="gopage('muni')">