How to set multiple select options by default from array - php

I'm trying to retrieve options/values from my database in the from of an array 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.
//data in database
$mytitle = array(
'Arbitrator',
'Attorney',
'Student',
'Other'
);
//data for multiple select
$title = array(
'Judge' ,
'Magistrate' ,
'Attorney' ,
'Arbitrator',
'Title Examiner' ,
'Law Clerk','Paralegal' ,
'Intern' ,
'Legal Assistant',
'Judicial Assistant',
'Law Librarian' ,
'Law Educator' ,
'Attorney',
'Student',
'Other'
);
echo "<select name='title[]' multiple='multiple'>";
$test = implode(',', $mytitle);
for ($i=0; $i<=14; $i++) {
if($test == $title[$i]) {
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}
else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
echo "</select>";

I think you may have a logic error. Try this as your loop:
foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}

Use the in_array() function.
for ($i=0; $i<=14; $i++) {
if(in_array($title[$i], $mytitle)){
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}

Very simple with the help of jQuery where the select has the id test
$('#test option').attr('selected', 'selected');
JSFiddle Example

Related

Set the selected value in select2 multiple using PHP

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 = "";
}

Codeigniter getting multiple data in foreach in controller

I have a problem regarding my foreach loop wherein i cannot access the first array or the array[0] and i dont know the problem.
here is the controller:
$this->SessionCheck();
$this->user->initialize($this->session->userdata('userid'));
$this->load->model('project_model', 'Project');
$ProjectID = $this->input->post('ProjectID');
/***************** Intialize Project model ******************/
$this->Project->Initialize($ProjectID);
$Options = Work_breakdown_structure::$WithBaseTaskID;
//$PhaseTaskID = (int)$this->input->get_post('TaskID',TRUE);
$PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->phaseList = $this->Project->LatestApplicablePlan->WBS->GetPhaseList($Options);
if($PhaseTaskID == null)
{ }
else
{
foreach($PhaseTaskID as $index=>$value)
{
$finalArr[$value['TaskName']] = $value['BasetaskID'];
$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($finalArr[$value['TaskName']], $Options);
}
echo print_r($finalArr);
for($x = 1 ; $x < 2 ; $x++)
{
//$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($phaseID, $Options);
}
}
$postlist->project = $ProjectID;
return $this->load->view('MyToDoPhaseDropdown', $postlist);
here is my view:
echo '<td style="padding-top:5x;font-size:14px;" colspan="2"> <br> Phases : ';
echo '<select id="phases_select" style="width:400px;" onchange="search_filter()" >';
echo '<option value="0" selected="selected"> Select Project Phase </option>';
foreach($phaseList as $row)
{
if(preg_match("/^CYCLE/", strtoupper($row['TaskName'])))
{
foreach($row['Child'] as $child)
{
echo '<option value="'. $child['TaskID']. '">';
echo $row['TaskName'].' > '.$child['TaskName'] . '</option>';
}
}
else
{
if($Iterate['BaseTaskID'] != $row['TaskID'])
{
echo '<option value="'. $row['TaskID']. '">';
echo $row['TaskName'].'</option>';
}
foreach($taskList as $Iterate)
{
if($row['TaskID'] == $Iterate['BaseTaskID'] )
{
echo '<option value="'. $row['TaskID']. '">';
echo $Iterate['TaskName'].' '.$Iterate['IterationNumber']. '</option>';
}
}
}
}
echo '</select>';
echo '</td>';
The problem is that i need to get all the values into an array to pass it to the view. but i only get the latest value which is the 2nd data that i retrieve in the database.
What you are doing wrong is :
return $this->load->view('MyToDoPhaseDropdown', $postlist);
You need to set the data in a variable to be accessible in view : http://codeigniter.com/user_guide/general/views.html
$data = array('title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message');
$this->load->view('MyToDoPhaseDropdown', $data);
And in view file : MyToDoPhaseDropdown.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>

selecting option from select element with php

I have a database field country which I want to query and select that country option from a select element. Is there any way to do this without adding:
if (query->country == "<some country>"){echo "selected"}
in every single option tag? As there are hundreds of country options. Here is a little example of the code. Thank you.
$query = $query->fetch_object();
// which ever country is held in the variable `$query->country` should be selected
echo"<select>
<option>Afghanistan</option>
......
......
<option>Zimbabwe</option>
</select>";
Don't you have a list of all countries on your server?
$countries = ["Afghanistan", ... , "Zimbabwe"];
You could do something like this:
$selection = "Some country";
echo "<select>";
foreach($countries as $country)
{
if($country == $selection)
echo "<option selected>" . $country . "</option>";
else
echo "<option>" . $country . "</option>";
}
echo "</select>";
The IF still needs to be "placed" on every <option> but as a programmer you should do something like this:
$options = array( 'Afghanistan', '...', 'Zimbabwe' );
foreach( $options as $option )
{
$selected = ( $query->country == $option )? ' selected': '';
echo '<option' . $selected . '>' . $option . '</option>';
}
and if you're unfamiliar with ternary operator, the $selected = ... part above can be written like this:
if ( $query->country == $option )
{
$selected = ' selected';
}
else
{
$selected = '';
}

Get data from DB to set as default in dropdown HTML/CSS/MYSQL/PHP

Hello guys I want to get data from the DB to set as default/selected in my dropdown.
I have a page named Update Project, in that page I have a dropdown component that is filled by records from my data, however I want to set the selected value from the query result.
This is what I've tried so far:
$st_ac = $conn->prepare( "SELECT p.project_code, m.type
FROM tblprojects as p
JOIN tblprojectsmaster as m
ON p.project_code = m.project_code
WHERE p.project_code = :code" );
$st_ac->execute(array(':code' => $code));
$result = $st_ac->fetch(PDO::FETCH_ASSOC);
$ptype = $result['type']; // the data to be selected in the dropdwon
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value"' . $type . '"';
if($ptype == $type)
echo 'selected="selected"';
echo '>' . $description . '</option>';
echo '<br />';
?>
<option value="<?php echo $type; ?>"><?php echo $description; ?></option>
<?php
}
?>
But I can't be able to achieve what I want. Any ideas? Your help will be truly appreciated. Thanks.
Try this
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value="'.$type.'"';
if($ptype == $type)
{
echo 'selected="selected"';
}
echo '>'.$description.'</option>';
}
?>
May be you can use like this
echo '<option value="' . $type . '"'; if($ptype == $type) { echo 'selected="selected" } >'; echo $description . '</option>'; echo '<br />';

Dropdown form with selected value from variable

I have the current theme for my script stored in my config file (JQUERY_THEME) how can i make that the preselected value in the dropdown list.
$jquerytheme = JQUERY_THEME;
$themes = array("base", "black-tie", "blitzer", "cupertino", "dark-hive", "dot-luv", "eggplant", "excite-bike", "flick", "hot-sneaks", "humanity", "le-frog", "mint-choc", "overcast", "pepper-grinder", "redmond", "smoothness", "south-street", "start", "sunny", "swanky-purse", "trontastic", "ui-darkness", "ui-lightness", "vader");
echo "<p><select name=\"jquerytheme\">";
foreach ($themes as $value) {
echo "<option value=\"$value\">". ucfirst($value) . "</option>";
}
echo "</select></p>";
If you want a option preselected you must use the selected attribute in the option:
echo "<p><select name=\"jquerytheme\">";
foreach ($themes as $value) {
$selected = ($value == $jquerytheme) ? 'selected="selected"' : '';
echo "<option $selected value=\"$value\">". ucfirst($value) . "</option>";
}
echo "</select></p>";

Categories