How do I make a column inside select option in HTML/PHP? - php

So, I have a select option HTML where the data is got from json_decode(file_get_contents("myAPI.com")) and it looked like this:
note : the - is how I divide each data manually.
As you can see, the result is not neat, so tight, and hard to read.
I've tried using Javascript like this :
var spacesToAdd = 5;
var biggestLength = 0;
$("#pks_bank option").each(function(){ var len = $(this).text().length;
if(len > biggestLength){
biggestLength = len;
} }); var padLength = biggestLength + spacesToAdd;
$("#pks_bank option").each(function(){
var parts = $(this).text().split('+');
var strLength = parts[0].length;
for(var x=0; x<(padLength-strLength); x++){
parts[0] = parts[0]+' ';
}
$(this).text(parts[0].replace(/ /g, '\u00a0')+'+'+parts[1]).text; });
But the result is getting worse and farther like this :
Below is my select option code :
<select name='pks_bank' id='pks_bank' data-widget='select2' class='multisel'
style='width:65%; padding-bottom:5px;padding-top:5px;'>
<option value='no'>- Pilih PKS Bank - </option>
<?php
foreach ($list_pks_bank as $data) {
$id_wok = $data->PKS1 . '/' . $data->PKS2 . '/' . $data->PKS3 . '/' . $data->PKS4;
$wok = $data->NMBNK . ' - ' . $data->NOPKS1 . ' - ' . $data->NOPKS2;
echo "<option value='" . $data->PKS2 . "'>" . ucwords(strtoupper($wok)) . "</option>";
}
?>
</select>
How do I make a column inside select option in HTML/PHP? So it would be like this :
In .NET I can give the Combo Box Column > ListBoxColumn property

Related

jquery.load("something.php") not working well

i have a something.php which will print the option of dropdownlist,\
then i load the .php file with
$("#dropdownlist").load("something.php");
after i load, the output is displayed, but when i change the selected value, in debug mode i din not saw a selected="selected" on the option of dropdownlist and i cannot set a selectedvalue to the dropdownlist also with
$("#dropdownlist").val("2");
any one know why this happen and how can i solve it?
add-on code
--print option on .php--
while (isset($StatusArr[$loopCount])) {
if ($loopCount == 0) {
$selected = "selected='true'";
} else {
$selected = "";
}
echo "<option value='"
. $StatusArr[$loopCount][0]
. "' "
. $selected
. " >"
. $StatusArr[$loopCount][1]
. "</option>";
$loopCount ++;
}
---call in .js----
$('#select').load("../something.php", function (respond, fstatus, xhr) {
if (fstatus === "success") {
if (status !== "missing") {
$('#status').prop("selectedIndex", 3);
}
} else {
alert("Load data " + fstatus + "\n" + xhr.status + " " + xhr.statusText);
}
});
$("#dropdownlist").prop("selectedIndex", 1);
This jQuery code sets the selected option of the dropdownlist to the 2nd option.

About the evil of eval: How to clean up

I'm building a site that will (eventually) be the front-end for a game. I want to be able to dynamically build a list of "powers" that the user is able to purchase. In order to build these lists, I'm using a PHP-based SQL query, then passing it to Javascript for dynamic choices (some powers have prerequisite powers).
I know there's a simpler way to do what I'm doing, but I'm not super concerned with that right now (I will be later, but I'm trying to get this functional and then clean) (again, I know this is non-optimal).
I'm using eval to parse which divs to show, and I want to know how not to.
I'm having issues getting my div names built right in the first place.
Here's my code:
Javascript (separate file)
function upgradeList(passed)
{
var PowerArray = [];
var DetailPowerID = [];
var EscapedPowerID = [];
PowerArray.push([]);
PowerArray = eval(passed);
var OutputThing="";
for (i=0;i<PowerArray.length;i++)
{
DetailPowerID[i] = 'detail' + PowerArray[i][0];
EscapedPowerID[i] = "'" + DetailPowerID[i] + "'";
}
for (i=0;i<PowerArray.length;i++)
{
OutputThing = OutputThing + "<br><a href='#' onClick='showUpgradeDetails(" + DetailPowerID[i] + ")'>" + PowerArray[i][2] + "</a><div class='hidden' id='" +
DetailPowerID[i] + "'>" + PowerArray[i][3] + "</div>"; }
document.getElementById("secondUpgrade").innerHTML=OutputThing;
document.getElementById("secondUpgrade").style.display='block';
}
}
PHP writing HTML and JS:
{$AbleToUpgrade and $UpgradeList are both 2d arrays built from SQL queries)
echo "<script name='UpgradeList'>";
settype($UpgradesListSize[$i],"int");
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "var UpgradeList" . $AbleToUpgrade[$i][0] . " = new Array();";
for ($j=0;$j<=$UpgradesListSize[$i];$j++)
{
echo "UpgradeList" . $AbleToUpgrade[$i][0] . ".push(Array('"
. $UpgradeList[$i][$j][0] . "', '"
. $UpgradeList[$i][$j][1] . "', '"
. $UpgradeList[$i][$j][2] . "', '"
. $UpgradeList[$i][$j][3] . "', '"
. $UpgradeList[$i][$j][4] . "'));";
}
}
echo "</script>";
... and, later...
echo "<div id='SpendUpgrade'>
Select power to upgrade:
<ul>";
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "<li><a href='#' name='UpgradeList" . $AbleToUpgrade[$i][0] . "' onClick='upgradeList(this.name)'>" . $AbleToUpgrade[$i][1] . " - " . $AbleToUpgrade[$i][2] . "</a></li>";
}
echo "</select>
<div id='secondUpgrade' class='hidden'>
</div>
<div id='thirdUpgrade' class='hidden'>
</div>
</div>";
When I load the page, I wind up with generated text like this:
Real Armor
and the corresponding div:
<div class="hidden" id="detail21" style="display: none;">Your armor only works in the Waking</div>
In order to get the div to show (display:block;), I need to call the function like so:
showUpgradeDetails("detail21")
but I can't make JS / PHP write the quotes correctly. Help (with any or all of this?) please!
I found a resolution, and it wasn't JSON.parse().
I changed PowerArray = eval(passed); into PowerArray = window[passed];.
Because passed contains the name of a variable, and is not the variable itself, I couldn't work directly with it. However, because it was a string that held exclusively the name of a globally-defined variable, I could pass it to the window[] construct and have it work.

PHP output mySQL results into sortable columns

My app executes a query that returns it's results to a listview. The results are currently displayed in a single column, with a variable amount of rows depending on the query results. The single column displays a patient names and a birth dates for each patient.
I want to make my results display in two columns the first will contain names and the second birth dates. I also need to allow users to sort the result rows by either column. I've tried incorporating tables into my code and rearranging the set up of my <UL> but I can't get anything to work.
Here is my query/row output code:
if(isset($_POST['dt']) && $_POST['dt'] != '')
{
$dts = $_POST['dt'];
$dts = mysql_real_escape_string($dts);
$edit_date = str_replace("/", "-", $dts);
$edit_date = explode(" ", $edit_date);
$edit_date = explode("-", $edit_date[0]);
$string = $edit_date[2] . "-" . $edit_date[0] . "-" . $edit_date[1];
$query = "select * from VISIT JOIN PATIENT ON VISIT.PATIENT_ID=PATIENT.ID where VISIT.VISIT_DATE like '%".$string."%' ORDER BY PATIENT.LAST_NAME;";
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
$previous_letter = '';
while($row = mysql_fetch_array($res))
{
$id = $row['ID'];
$letter = strtoupper(substr($row['LAST_NAME'],0,1));
echo "<li data-theme=\"c\" id=\"patient_name\">\n";
echo "<a href=\"deeschdeesch.php?id=" . $id . "&fname=" . $row['FIRST_NAME'] . "&lname=" . $row['LAST_NAME'] . "\" rel=\"external\">\n";
$date = $row['BIRTH_DATE'];
$date = explode(" ", $date);
$date = explode("-", $date[0]);
echo ucwords(strtolower($row['FIRST_NAME'] . " " . $row['LAST_NAME'])) . " - " . $date[1] . "-" . $date[2] . "-" . $date[0];
echo "</a>\n";
echo "</li>\n";
$i++;
}
}
else
{
$edit_date = str_replace("/", "-", $dts);
$edit_date = explode(" ", $edit_date);
$edit_date = explode("-", $edit_date[0]);
$string = $edit_date[2] . "-" . $edit_date[0] . "-" . $edit_date[1];
echo "<div id='no_result'>There were " . $count . " results found, but the input was " . $string . "</div>";
}
}
Results are output here:
<div data-role="content" style="padding: 15px">
<ul class="ui-body ui-body-d ui-corner-all" id="results" data-role="listview" data-divider-theme="b" data-filter-theme="a" data-inset="true" data-filter="false">
</ul>
</div>
JS involved:
$(function(){
$('#datepicker').datepicker({
inline: true,
showOn: "button",
buttonImage: "images/calendar.gif",
showAnim: "slideDown",
changeMonth: true,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var dt = dateText;
if(dt != '')
{
$.ajax
({
type: "POST",
url: "search_date.php",
data: "dt="+ dt,
success: function(option)
{
$("#results").html(option).listview("refresh");
}
});
}
else
{
$("#results").html("");
}
return false;
}
});
});
Can anyone point me in the right direction on how to separate my results into multiple columns and/or make them sortable? Please and thank you all.
There are many javascript plugins out there to fulfil the result you want. Take a look at these two:
tablesorter - tablesorter is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes;
DataTables - DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

jquery add to array then submit and pass data not working

My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']

selected option in select dissappears on reload

Once it loads in my page, if nothing has been saved in the DB table, all options are shown. As soon as i make a selection and reload the page, the selected option dissapears from the list and isn`t reloaded in the dropdown. Instead, it displays the next value which takes the place of the selected one.
if i check the SQL statement and the $str, it does load all the options except the one which is selected which is in $getBris (it has a value).
What could be causing my select to not display my selected option and instead removing it from the list?
*It specifically doesnt work in IE8, wasnt working in Firefox but now it does
<script src="validation.js" type="text/javascript"></script>
<html>
<body onLoad="checkSecondValue();">
</body>
</html>
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
// ORDER BY RAND()
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$getBris = $_GET['bris'];
$getBris = $getBris - 1;
print_r("bris is : "+ $getBris);
if($getBris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value='999'>Choisir un bris</option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $getBris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
$i++;
}
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
echo "<script type=\"text/javascript\">alert('test');checkSecondValue();</script>";
}
?>
Use your browser's View Source feature to inspect the actual HTML you are generating (which is, in fact, the only see the browser ever sees). It looks like you're inserting random single quotes.
Update:
<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>"
... will render as:
<option value='blah' selected '>blah</option>
It's the only error I've cared to spot but an HTML validator should find them all. Also, I recommend you use this syntax:
<option value="blah" selected="selected">blah</option>
A construct like this
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
is highly wasteful of space and forces you to duplicate a big chunk of html whose only difference is the "selected" attribute. Why not do something like this:
$selected = ($getBris == 12) ? ' selected' : '';
$str .= "<option value=12{$selected}>Autre</option>";

Categories