In my view I have the following select menu that states what type of form types are available:
<label for="add_fields_type">Type: </label>
<select name="add_fields_type" id="add_fields_type">
<option value="input">Input</option>
<option value="textarea">Text Area</option>
<option value="radiobutton">Radio Button</option>
<option value="checkbox">Check Box</option>
</select>
In my controller I currently have the following but I am unsure how to make is so that if $_REQUEST['add_fields_type'] is = to lets say radiobutton then it will display that respective code.
Controller:
if (isset($_REQUEST['add_fields_type']))
{
echo $_REQUEST['add_fields_type'];
}
if (isset($_REQUEST['add_fields_type'])) {
if ($_REQUEST['add_fields_type'] == 'input') {
// echo stuff for input
}
else if ($_REQUEST['add_fields_type'] == 'textarea') {
// echo stuff for textarea
}
else if ($_REQUEST['add_fields_type'] == 'radiobutton') {
// echo stuff for radiobutton
}
else if ($_REQUEST['add_fields_type'] == 'checkbox') {
// echo stuff for checkbox
}
}
Another way, using the switch code that swapnesh mentioned (slightly more concise than having multiple if statements and will stop when it hits the right case):
if (isset($_REQUEST['add_fields_type']))
{
switch($_REQUEST['add_fields_type'])
{
case('input'):
// echo stuff for input
break;
case('textarea'):
// echo stuff for textarea
break;
case('radiobutton'):
// echo stuff for radiobutton
break;
case('checkbox'):
// echo stuff for checkbox
break;
default:
// echo stuff if the other cases fall through
break;
}
}
Related
I'm working on a school project and i need some suggestions. It is a HTML/PHP/SQL project where users can give their input about gaming experiences. As an admin you have to be able to see the names of the users that chose for certain gaming categories. This needs to be showed in tables using PHP and MySQL.
I have now finished this page, it is working like a charm and i can see all the users input. But the problem is that i have about 600 lines of code since i have 12 different div's with MySQL statements and tables.
Currently my code is seperated into 3 parts, the html select dropdown, 12 different div's with query's that generates tables, and jquery to show / hide the tables based on the select dropdown
I am hoping someone could give me a suggestion on how to shorten my code, since 600 lines of code is crazy and i am aware that it could be shorter but i just can't figure out how.
The HTML Select:
<select name="type" id="type" style="margin-left:57px; width:153px;">
<option name="select" value="select">Selecteren..</option>
<optgroup label="Hoe spelen mensen?">
<option name="alleen" value="alleen">Meestal alleen</option>
<option name="fysiek" value="fysiek">Meestal samen fysiek</option>
<option name="online" value="online">Meestal samen online</option>
</optgroup>
<optgroup label="Categorieën bordspellen">
<option name="alleen" value="kaartspellen">Kaartspellen</option>
<option name="fysiek" value="strategische">Strategische bordspellen</option>
<option name="online" value="fantasy">Fantasy bordspellen</option>
<option name="online" value="klassiek">Klassieke gezelschapspellen</option>
</optgroup>
<optgroup label="Categorieën computergames">
<option name="alleen" value="sport">Sport games</option>
<option name="fysiek" value="adventure">Adventure games</option>
<option name="online" value="war">War games</option>
<option name="online" value="strategischegames">Strategische games</option>
</optgroup>
<optgroup label="Gebruikers">
<option name="alle" value="alle">Alle gebruikers</option>
</optgroup>
1 div with a table (as example, since there are 12 different of these)
<div class="row" id="wargames">
<?php
$war = "SELECT * FROM form where categorie = 'wargames'";
$querywar = mysqli_query($conn, $war);
if (!$querywar) {
die('SQL Error: ' . mysqli_error($conn));
}
?>
<table class="data-table">
<caption class="title">Deze mensen spelen meestal de categorie War
games</caption>
<thead>
<tr>
<th>Naam</th>
<th>Woonplaats</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($querywar)) {
echo '<tr>
<td style="text-align:center">' . $row['naam'] . '</td>
<td style="text-align:center">' . $row['woonplaats'] .
'</td>
<td style="text-align:center">' . $row['email'] . '</td>
</tr>';
}
?>
</tbody>
</table>
my jquery
$(function() {
$('#row_dim').hide();
$('#type').change(function(){
if($('#type').val() == 'alleen') {
$('#alleen').show();
} else {
$('#alleen').hide();
}
if($('#type').val() == 'fysiek') {
$('#fysiek').show();
} else {
$('#fysiek').hide();
}
if($('#type').val() == 'online') {
$('#online').show();
} else {
$('#online').hide();
}
if($('#type').val() == 'kaartspellen') {
$('#kaartspellen').show();
} else {
$('#kaartspellen').hide();
}
if($('#type').val() == 'strategische') {
$('#strategische').show();
} else {
$('#strategische').hide();
}
if($('#type').val() == 'fantasy') {
$('#fantasy').show();
} else {
$('#fantasy').hide();
}
if($('#type').val() == 'klassiek') {
$('#klassiek').show();
} else {
$('#klassiek').hide();
}
if($('#type').val() == 'sport') {
$('#sportgames').show();
} else {
$('#sportgames').hide();
}
if($('#type').val() == 'adventure') {
$('#adventure').show();
} else {
$('#adventure').hide();
}
if($('#type').val() == 'war') {
$('#wargames').show();
} else {
$('#wargames').hide();
}
if($('#type').val() == 'strategischegames') {
$('#strategischegames').show();
} else {
$('#strategischegames').hide();
}
if($('#type').val() == 'select') {
$('#selected').show();
} else {
$('#selected').hide();
}
if($('#type').val() == 'alle') {
$('#gebruikers').show();
} else {
$('#gebruikers').hide();
}
});
$( document ).ready(function() {
if($("#type").attr("selectedIndex") !== 0) {
$('#selected').show();
$('#strategischegames').hide();
$('#wargames').hide();
$('#adventure').hide();
$('#sportgames').hide();
$('#klassiek').hide();
$('#fantasy').hide();
$('#strategische').hide();
$('#kaartspellen').hide();
$('#online').hide();
$('#fysiek').hide();
$('#alleen').hide();
$('#gebruikers').hide();
}
});
});
One think to shorten would be $('#type').change(...) handler:
$('#type').change(function () {
const map = {
'alleen': 'alleen',
'fysiek': 'fysiek',
'online': 'online',
'kaartspellen': 'kaartspellen',
'strategische': 'strategische',
'fantasy': 'fantasy',
'klassiek': 'klassiek',
'sport': 'sportgames',
'adventure': 'adventure',
'war': 'wargames',
'strategischegames': 'strategischegames',
'select': 'selected',
'alle': '#gebruikers',
};
Object.keys(map).forEach(key => {
if ($('#type').val() == key) {
$('#' + map[key]).show();
} else {
$('#' + map[key]).hide();
}
});
});
As you can see, I declaratively map values to IDs, then process all of them in a cycle.
Next step would be generalizing that show/hide functionality:
function show(type) {
const map = {
'alleen': 'alleen',
'fysiek': 'fysiek',
'online': 'online',
'kaartspellen': 'kaartspellen',
'strategische': 'strategische',
'fantasy': 'fantasy',
'klassiek': 'klassiek',
'sport': 'sportgames',
'adventure': 'adventure',
'war': 'wargames',
'strategischegames': 'strategischegames',
'select': 'selected',
'alle': '#gebruikers',
};
Object.keys(map).forEach(key => {
if (type == key) {
$('#' + map[key]).show();
} else {
$('#' + map[key]).hide();
}
});
}
With that function, your change and ready event handlers can be shortened like this:
$('#type').change(function () {
show($('#type').val());
});
$(document).ready(function () {
if ($("#type").attr("selectedIndex") !== 0) {
show('select');
}
});
Re PHP part, I see only one piece, so, I don't know what is common with others, but as a general rule:
Note common things
Note differences, e.g. different values passed to same pieces of code
Move differences to variables before common things
Now you can easily transform piece of code into a function -- just make a function with things from p.3 as parameters
Call that function as many times as needed, or maybe in a loop -- this is exactly what I did with your JS code at the top of my answer
And, of course, your HTML screams "extract data structure from me and format it into tags". In other words, separate data from presentation, e.g.:
<?php
$data = [
[
'value' => 'select',
'text' => 'Selecteren..',
'childrenCaption' => 'Hoe spelen mensen?',
'children' => [
'alleen' => 'Meestal alleen',
'fysiek' => 'Meestal samen fysiek',
'online' => 'Meestal samen online',
],
],
];
function formatOptions($data) {
foreach ($data as $section) {
echo "<option name=\"$section[value]\" value=\"$section[value]\">$section[text]</option>\n";
echo "<optgroup label=\"$section[childrenCaption]\">\n";
foreach ($section['children'] as $value => $text) {
echo " <option name=\"$value\" value=\"$value\">$text</option>\n";
}
echo "</optgroup>\n";
}
}
formatOptions($data);
And sample output looks like this:
<option name="select" value="select">Selecteren..</option>
<optgroup label="Hoe spelen mensen?">
<option name="alleen" value="alleen">Meestal alleen</option>
<option name="fysiek" value="fysiek">Meestal samen fysiek</option>
<option name="online" value="online">Meestal samen online</option>
</optgroup>
As you can see, modifying $data variable is much easier than maintaining that much of HTML code.
There is more room from improvement, but this is a good start, I guess.
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";
}
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
<select name="year"><?=options(date('Y'),1900)?></select>
<select name="month"><?php echo date('m');?><?=options(1,12,'callback_month')?></select>
<select name="day"><?php echo date('d');?><?=options(1,31)?></select>
PHP
function options($from,$to,$callback=false)
{
$reverse=false;
if($from>$to)
{
$tmp=$from;
$from=$to;
$to=$tmp;
$reverse=true;
}
$return_string=array();
for($i=$from;$i<=$to;$i++)
{
$return_string[]='<option value="'.$i.'">'.($callback?$callback($i):$i).'</option>';
}
if($reverse)
{
$return_string=array_reverse($return_string);
}
return join('',$return_string);
}
function callback_month($month)
{
return date('m',mktime(0,0,0,$month,1));
}
What should i make to get the current month and date in the corresponding dropdowns as starting values, as it is the case with years (2013).
Try like following:
Added new param type to options() function
<select name="year"><?=options('year' ,date('Y'),1900)?></select>
<select name="month"><?php echo date('m');?><?=options('month', 1,12,'callback_month')?></select>
<select name="day"><?php echo date('d');?><?=options('day', 1,31)?></select>
<?php
function options($type, $from,$to,$callback=false)
{
$reverse=false;
switch ($type)
{
case "year":
$current = date('Y');
break;
case "month":
$current = date('m');
break;
case "day":
$current = date('d');
break;
}
if($from>$to)
{
$tmp=$from;
$from=$to;
$to=$tmp;
$reverse=true;
}
$return_string=array();
for($i=$from;$i<=$to;$i++)
{
$selected = ($i == $current ? " selected" : "");
$return_string[]='<option value="'.$i.'" '.$selected.'>'.($callback?$callback($i):$i).'</option>';
}
if($reverse)
{
$return_string=array_reverse($return_string);
}
return join('',$return_string);
}
function callback_month($month)
{
return date('m',mktime(0,0,0,$month,1));
}
?>
just retreive the current date FIRST and use a for loop to subtract each year
Use selected Attribute:
e.g.
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
Fiddle here: http://jsfiddle.net/dd3FU/
Just put it inside an if statement.
Enjoy!
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>