PHP dropdown default value - php

I have this code,How would you set a default selection in this dropdown menu.
<tr><td class="tdt">
<?php te('Hypervisor');?>:</td> <td title='Add more from Hypervisor menu'>
<select validate='required:true' class='mandatory' name='hyp'>
<option value=''>Select</option>
<?php
foreach ($hyper as $a) {
$dbid=$a['id'];
$atype=$a['typedesc']; $s="";
if (isset($hyp) && $hyp==$a['id']) $s=" SELECTED ";
echo "<option $s value='$dbid' title='$dbid'>$atype</option>\n";
}
echo "</select>\n";
?>
Thanks for your help.
UPDATE:
I have a table connected to this code called hypervisors.in that table theres id field and typedesc field.I'd like to set "ESXi" as the default value which is represented by an ID num 1.
Update 2:
$sql="SELECT id,typedesc FROM hypervisors";
$sth=db_execute($dbh,$sql);
while ($r=$sth->fetch(PDO::FETCH_ASSOC))
$hyper[$r['id']]=$r;
that is SQL query

use this:
foreach ($hyper as $a) {
$dbid=$a['id'];
$atype=$a['typedesc'];
if (isset($hyp) && $hyp==$dbid) {
echo "<option selected='selected' value='$dbid'>$atype</option>\n";
} else {
echo "<option value='$dbid'>$atype</option>\n";
}
}

With selected within the option tag, you set the selected default value of your dropdown
http://www.w3schools.com/tags/att_option_selected.asp
if (isset($hyp) && $hyp==$a['id']){
$s=" SELECTED ";
echo "<option $s value='$dbid' selected>$atype</option>\n";
}
else {
echo "<option value='$dbid'>$atype</option>\n";
}

Related

Disable select option when other specifig value is selected

I have a question by these given information:
private function loadIntervallOptions($intervallid = 1, $intervallfactor=1){
echo "<select name='intervallfactor'>";
for($intervallnumber=1;$intervallnumber<10;$intervallnumber++){
$checked = "";
if($intervallnumber== $intervallfactor){
$checked = "selected";
}
echo "<option $checked>$intervallnumber</option>";
}
echo "</select>";
echo "<select name='intervallid'>";
for($i=0;$i<count($this->todo_intervall);$i++){
echo "<option value='{$this->todo_intervall[$i]->getintervallid()}' ";
if($this->todo_intervall[$i]->getIntervallid() == $intervallid){
echo "selected";
}
echo ">{$this->todo_intervall[$i]->getIntervall()}</option>";
}
echo "</select>";
}
What I want to do:
If intervallid=1 I want to hide the select 'intervallfactor'. Is this possible?
Thank you in advance!
EDIT:
I'm trying this but it won't work
$('.intervallid').change(function(e) {
if ($('.intervallid').val()==1){
$('.intervallfactor').attr('disabled','disabled');
}
else{
$('.intervallfactor').removeAttr('disabled');
}
});
$('.intervallid').trigger('change');
You are trying to reference the html element using a class name .intervallid which doesnt exist.
either you should use $('select[name="intervalid"]) or add an id to the select from php and, use that to reference the element.
PHP
echo "<select name='intervallid' id='intervall_id'>";
JS
$('#intervall_id').attr('disabled', 'true')

How to get the value which user has selected in php?

I have a little problem here. I have a list, which is:
<form action="display.php" method="post">
<select name="holiday">
<option value="month">Kiekvieno mėnesio skaičiavimas</option>
<option value="day">Kiekvienos dienos skaičiavimas</option>
</select>
<br> <br>
<input type="submit" name="select" value="Pasirinkti" />
</form>
What I need to do is that when the user selects value ="month", php code would do one action, and when the user selects value ="day", php code would do another action?
My php code looks like this:
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
else if ($selectedValue == $_POST['month']) {
$todaysDate = new DateTime();
while ($employee = $select->fetch()){
$employmentDateValue = new DateTime($employee['employment_date']);
// Comparing employment date with today's date
$differenceBetweenDates = date_diff($employmentDateValue, $todaysDate);
$workMonths = $differenceBetweenDates->y * 12 + $differenceBetweenDates->m;
$holidayDays = $workMonths *4;
echo "<tr>";
echo "<td>".$employee['name']."</td>";
echo "<td>".$employee['surname']."</td>";
echo "<td>".$employee['employment_date']."</td>";
echo "<td>".$workMonths."</td>";
echo "<td>".$holidayDays."</td>";
echo "</tr>";
}
}
else {
echo "Lalalala";
}
?>
I've tried to do so with $_POST['select'], but it doesn't work. Thanks for any help guys
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
if ($selectedValue == 'month') {
}
else if ($selectedValue == 'day') {
}
else{
echo "Lalalala";
}
}
?>
You need to do $_POST['holiday'], so change:
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
to
if($_POST['holiday']){
// Storing selected value in a variable
$selectedValue = $_POST['holiday'];
}
You also need to change the line:
else if ($selectedValue == $_POST['month']) {
So it's not part of the original if statement:
if ($selectedValue == 'month') {
// your code
}
else {
echo "Lalalala";
}

Option Menu with Last Record as Default

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

how to display particular value in dropdown in php?

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

Creating combobox and checkboxes with jQuery and CodeIgniter

I have combobox named catid, which is filled with categories. On change, I am filling the content on other
2 comboboxes and I am adding checkboxes in my form, which are all based on selected category.
So three comboboxes in total, categories (#catid), subcategories (#catid2) and manufacturers (#manufacturerid)
in this order.
When there are no subcategories, everything is nice and smooth. In the subcategory combobox, i get the message
there are no subcategories, i am filling the manufacturers combobox with manufacturers from that category,
and i am drawing the comboboxes again related to this category.
Problem arise when sub category exist. I am trying using on change event to fetch my checkboxes, related to that subcategory.
I get undefined value.
Here is my code:
Controller:
public function __construct() {
parent::__construct();
$this->load->model('addsCategoriesModel');
$this->load->model('addsTypesModel');
$this->load->model('colorsModel');
$this->load->model('geographicAreasModel');
$this->load->model('categoriesFiltersModel');
}
// function index has been ommited for the sake of simplicity
function get_dropdown_values($catid){
$this->load->model('manufacturersModel');
$this->db->select('manufacturerid,manufacturername');
$this->db->where("catid = $catid");
$result = $this->manufacturersModel->get();
//echo form_dropdown('manufactirerid', $result, NULL, 'id="manufacturerid"');
echo "<select name='manufacturerid' id='manufacturerid' class='styled_select'>";
//"<option value=".$result[]['manufacturerid'].">".$result[]['manufacturername']
foreach ($result as $key=>$value) {
echo "<option value=".$key['manufacturerid'].">".$value['manufacturername']."</option>";
}
echo "</select>";
}
function get_dropdown_values2($catid){
// create the second drop down, where parent id is the selected category
$this->db->select('catid,parentid,categoryname');
$this->db->where("parentid = $catid");
$result2 = $this->addsCategoriesModel->get();
if(count($result2) > 0){
echo "<select name='catid2' id='catid2' class='styled_select'>";
foreach ($result2 as $key=>$value) {
echo "<option value=".$key['catid'].">".$value['categoryname']."</option>";
}
echo "</select>";
} else {
echo "<select name='catid2' id='catid2' class='styled_select'>";
echo "<option value='0'>No subcategories</option>";
echo "</select>";
}
}
function get_categories_filters($catid3){
// create the checkboxes according to selected category
// case 1: if the category id is NOT 4
$this->db->where("catid = $catid3");
$result3 = $this->categoriesFiltersModel->get();
if(count($result3) > 0){
// start the foreach loop
foreach($result3 as $key=>$value){
echo "<div class='chb_group'>";
echo "<span class='custom_chb_wrapper'>";
echo "<input type='checkbox' name=" .$value['filterid'] ." class='zcheckbox'/>";
echo "<label>" .$value['filtername']. "</label>";
echo "</span>";
echo "</div>";
}
} else {
$result3 = "No checkboxes in this category";
echo $result3;
//$this->get_categories_filters2(22);
}
}
function get_categories_filters2($catid4){
// create the checkboxes according to selected category
$this->db->where("catid = $catid4");
$result4 = $this->categoriesFiltersModel->get();
if(count($result4) > 0){
// start the foreach loop
foreach($result4 as $key=>$value){
echo "<div class='chb_group'>";
echo "<span class='custom_chb_wrapper'>";
echo "<input type='checkbox' name=" .$value['filterid'] ." class='zcheckbox'/>";
echo "<label>" .$value['filtername']. "</label>";
echo "</span>";
echo "</div>";
}
} else {
//$result4 = "No checkboxes in this category";
$result4 = "Are you in filters2??";
echo $result4;
}
}
}
Here is my view:
<select name="catid" id="catid" class="styled_select" onchange="load_dropdown_content($('#manufacturerid'), this.value);load_dropdown_content2($('#catid2'), this.value);load_dropdown_content3($('#catid3'), this.value);">
<option value="0">Please select</option>
<?php
// foreach loop to fetch the categories
foreach ($adds_categories as $category){
echo "<option value=".$category['catid'].">".$category['categoryname']."</option>";
}
?>
</select>
</div>
<div class="select_wrapper">
<label><strong>Subcategory: </strong></label>
<select name="catid2" id="catid2" class="styled_select" onchange="load_dropdown_content4($('#catid3'), this.value);">
<option value="0">Please select</option>
</select>
</div>
For the sake of simplicity, I am not showing here the manufactirer combobox, with which i have no problem whatsoever and the checkboxes
And the javascript:
<script type="text/javascript">
function load_dropdown_content(field_dropdown, selected_value){
var result = $.ajax({
'url' : '<?php echo site_url('submit/get_dropdown_values'); ?>/' + selected_value,
'async' : false
}).responseText;
field_dropdown.replaceWith(result);
}
function load_dropdown_content2(field_dropdown, selected_value){
var result2 = $.ajax({
'url' : '<?php echo site_url('submit/get_dropdown_values2'); ?>/' + selected_value,
'async' : false
}).responseText;
field_dropdown.replaceWith(result2);
}
function load_dropdown_content3(field_dropdown, selected_value){
if(selected_value == 4){
load_dropdown_content4();
}
var result3 = $.ajax({
'url' : '<?php echo site_url('submit/get_categories_filters'); ?>/' + selected_value,
'async' : false
}).responseText;
$('#catid3').empty(); // DIV CATID3 IS THE DIV WHERE CHECKBOXES ARE CREATED
$("#catid3").append(result3);
}
function load_dropdown_content4(field_dropdown, selected_value){
var result4 = $.ajax({
'url' : '<?php echo site_url('submit/get_categories_filters2'); ?>/' + selected_value,
'async' : false
}).responseText;
$('#catid3').empty(); // DIV CATID3 IS THE DIV WHERE CHECKBOXES ARE CREATED
$("#catid3").append(result4);
alert(result4);
}
</script>
If anyone can help me to overcome that undefined error which I am getting from subcategories combobox, I will deeply appreciated.
Regards...
Instead of $("$cat3"), you can do like below also.
onchange = 'load_dropdown_content4("cat3",this.value)'
In load_dropdown_content4
function load_dropdown_content4(field_dropdown, selected_value)
{
//replace field_dropdown.replaceWith(result2);
$("#"+field_dropdown).replaceWith(result2);
}
Try this code.

Categories