I've been working on this nonstop and none of the online suggestions have worked.
I have a dynamically created table that refreshes every 5 seconds. There are checkboxes on the table, if you check a box it highlights the row. When the page refreshes all checked states are lost, I need them to be saved, either by local storage or a cookie or even writing out to a file.
Please help and thanks in advance.
My currently working code that does not retain the checked state:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div>';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
Here it is with nonworking solution:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script src="../../jquery.js"></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $("#checkbox-container :checkbox");
var $button = $("#checkbox-container button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
function updateStorage(){
$checkboxes.each(function(){
formValues[this.id] = this.checked;
});
formValues["buttonText"] = $button.text();
localStorage.setItem("formValues", JSON.stringify(formValues));
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on("change", function(){
updateButtonStatus();
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#" + key).prop('checked', value);
});
$button.text(formValues["buttonText"]);
</script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div id="checkbox-container">';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
here is the code from the page that answered the persistent checkbox question, this page works for me, but the code from it on my page does not.
<html >
<head>
<meta charset="UTF-8">
<title>CodePen - A Pen by SitePoint</title>
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
</style>
</head>
<body translate="no" >
<input type="text" placeholder="Type something here" />
<div id="checkbox-container">
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<button>Check All</button>
</div>
<script src='../../jquery.js'></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $('#checkbox-container :checkbox');
var $button = $('#checkbox-container button');
function allChecked() {
return $checkboxes.length === $checkboxes.filter(':checked').length;
}
function updateButtonStatus() {
$button.text(allChecked() ? 'Uncheck all' : 'Check all');
}
function handleButtonClick() {
$checkboxes.prop('checked', allChecked() ? false : true);
}
function updateStorage() {
$checkboxes.each(function () {
formValues[this.id] = this.checked;
});
formValues['buttonText'] = $button.text();
localStorage.setItem('formValues', JSON.stringify(formValues));
}
$button.on('click', function () {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on('change', function () {
updateButtonStatus();
updateStorage();
});
$.each(formValues, function (key, value) {
$('#' + key).prop('checked', value);
});
$button.text(formValues['buttonText']);
//# sourceURL=pen.js
</script>
</body>
</html>
Well, it's been a day, and I don't see anything here.
My assumption is that you guys are finding this just as difficult as I am.
I am still working on this and here is my logic.
I will have to get the insidehtml of one of the cells in the row as part of the onclick event, then set a cookie or use session to store the variable based on the row, and then an onload event that reads that session or cookie and checks the appropriate boxes and highlights the appropriate rows.
If anyone has any comments or suggestions, they are entirely welcome.
tia
Related
I want to try get a traffic light colour scheme with my time text where if the time is between 0.0000 and 10.0000 the text if green if between 10.0100 and 15.0000 the text is orange and between 15.0100 and 20.0000 then its red i cant get my function to run i may be missing something but im not sure what.
currently the mysql query returns result as 14.6263 with this value constantly changing
my current code is :
<!doctype html>
<html>
<head>
<title>time stats</title>
<style>
body {
background-color: black;
}
.box1 {
width: 300px;
height: 400px;
border: 15px solid yellow;
padding: 15px;
margin: 15px;
display: inline-block;
color: white;
font-size:40px;
color: lime;
.container {
text-align: center;
}
</style>
<body>
<div class="box1">
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','username','password','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="select avg(time_format(delivery_avg,'%i:%s')) as time_avg from test.del where location = 'yellow'";
$result = mysqli_query($con,$sql);
echo "<table>
<thead>
<th>time Average</th>
</thead>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['time_avg'] . "</td>";
echo "</tr>";}
echo "</table>";
mysqli_close($con);
?>
</div>
function updatecolor() {
//console.log('function called');
{
if ($box1.td < 10)
return '#00FF00';
else if ($box1.td >= 11 && $box1.td<= 15)
return = '#FFA500';
else if ($box1.td >= 16 && $box1.td<= 20)
return = '#ff0000';
}
});
}
var updateInterval = setInterval(updatecolor, 1000);
</body>
</html>
Here's a little function that will return your colors depending on the $valueToCheck parameter of the function:
<?php
function addColor($valueToCheck) {
{
if ($valueToCheck <= 10) {
return '#00FF00';
} else if ($valueToCheck >= 11 && $valueToCheck <= 15) {
return '#FFA500';
} else if ($valueToCheck >= 16 && $valueToCheck <= 20) {
return '#ff0000';
}
};
}
?>
Wrapped it in <?php ?> tags, since it's a PHP function.
Use it in your HTML like so:
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td style=\"color:" . addColor($row['time_avg']) . "\">";
echo $row['time_avg'];
echo "</td>";
echo "</tr>";
}
As for your code:
return = '#FFA500'; is not valid, remove the =.
If $box1 were available:
if ($box1.td < 10)
return '#00FF00';
else if ($box1.td >= 11 && $box1.td<= 15)
What about 10? You never check for 10>x>11.
In these days I tried to write a sort of registration-login system with php and mySql and somehow I managed to do it; now I want to put all the things in a new page with a pop up window: you press the button "register" or "login" and on the screen appears a window with all the stuff and things, that's what I did:
<!DOCTYPE html>
<html>
<head>
<title>FindMyChamp</title>
</head>
<body>
<style type="text/css">
.popUpBox{
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.4);
}
.popUpBoxBody{
margin: 15% auto;
padding: 15px;
background-color: #fefefe;
width: 30%;
}
.closeBtn{
float: right;
font-size: 28px;
}
.container{
width: 300px;
clear: both;
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.container input{
width: 100%;
clear: both;
}
#send{
width: 50%;
}
</style>
<h1>Test</h1>
<p id="popUpTrigger">Register</p>
<p>Login</p>
<div id="divPopUp" class="popUpBox">
<div class="popUpBoxBody">
<span id="popUpCloser" class="closeBtn">×</span>
<div class="container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Repeat Password: <input type="password" name="passwordCheck"><br><br>
<input value="Send" id="send" type="submit" name="sub">
</form>
<?php include('registration.php') ?>
</div>
</div>
</div>
<script type="text/javascript">
var btnOpen = document.getElementById("popUpTrigger");
var popUp = document.getElementById("divPopUp");
var btnClose = document.getElementById("popUpCloser")
btnOpen.onclick = function(){
popUp.style.display = "block";
}
btnClose.onclick = function(){
popUp.style.display ="none";
}
</script>
register.php:
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST["sub"])){
$username = $password = $passwordCheck = "";
$flag = true;
$con = mysql_connect('localhost','root','Testpass');
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Controllo se i campi sono vuoti
if(empty($_POST["username"])){
echo "The field 'Username' is required<br>";
} else{
$username = test_input($_POST["username"]);
}
if(empty($_POST["password"])){
echo "The field 'Password' is required<br>";
$flag = false;
} else{
$password = test_input($_POST["password"]);
}
if(empty($_POST["passwordCheck"])){
echo "The field 'Repeat Password' is required<br>";
$flag = false;
} else{
$passwordCheck = test_input($_POST["passwordCheck"]);
}
}
if($password == $passwordCheck && $password != ""){
mysql_select_db('tutorials');
$checkUsernameDuplicate = mysql_query("SELECT * FROM registration WHERE username = '$username'");
if(mysql_num_rows($checkUsernameDuplicate) <= 0){
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16,MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost). $salt;
$hash = crypt($password, $salt);
$sql = "INSERT INTO registration(username,password) VALUES('$username','$hash')";
$retvalue = mysql_query($sql,$con);
if(!$retvalue){
echo "Something went wrong";
} else{
echo "Dati inseriti";
//header("Location: http://localhost/database/login.php");
exit();
}
} else{
echo "Username aldready taken";
}
mysql_close($con);
}
elseif($flag){
echo "<p style='color: red;'>The two password must match</p>";
}
}
?>
Everything works fine, but, when I press the button 'send' the window disappears and all the datas are send to the database, that's ok but I want that the windows remains until the user decides to close it. How can I do that?
use ajax, you can execute your code in register.php without refreshing your page
http://api.jquery.com/jquery.ajax/
I am working on an inventory search for a local clothing store, and because of the way their website is setup, I need to run the php that pulls the data and organizes it run on the same page as the search form. (I assume this needs to be done with AJAX. I am very new to AJAX :P)
Here are the current files.
Search.php
<?php
include(dirname(__FILE__) . '/../inc/init.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf- 8" />
<title>Inventory | The Loft Ames</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="popup.css">
<link rel="stylesheet" type="text/css" href="../css/loft_fonts.css" />
<link rel="stylesheet" type="text/css" href="../css/loft_style.css" />
<link href="../admin/themes/css/bootstrap.min.css" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
a:link {
color: #FFF;
text-decoration: none;
}
a:visited {
text-decoration: none;
color: #FFF;
}
a:hover {
text-decoration: none;
color: #FFF;
}
a:active {
text-decoration: none;
color: #FFF;
}
.form-search{
text-align:left;
}
.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
background-color: black;
}
html, body { margin: 0; padding: 0; }
div#DP01 {
position:relative;
width:575px;
/*margin: 0 auto;*/
}th{
cursor:pointer;
}
</style>
</script>
</head>
<body>
<div id="layout">
<div id="DP01">
<br><h27><center>Search Our Inventory at The Loft</center></h27><br>
<form action="/test/results.php" method="post">
Search here: <input type="text" name="search"><br>
<input type="submit"><br>
<script type="text/javascript" src="jquery.min.js"></script>
<!--Click Me!-->
</form>
<br><br>
<!-- <h27><center>View Our Current Inventory</center></h27>
<center>
Show Latest Inventory
</center> -->
<br><br>
<h31><center>Please contact us if you have any additional questions <a class="popup" href="/popups/contact.html"><strong>here.</strong></a><br>or call us 515-232-9053.</center></h31>
<br><br>
</div>
</div>
<?php
include('footer.php');
?>
</body>
</html>
results.php
<?php
$search = $_GET['search'];
if ($search == "") {
echo "Please enter a query. <a href='/search.php'>Click Here</a> to go back";
break;
}
else {
$data = array('key' => $API_KEY,
/*'consignorId' => '1',*/
'query' => $search,
'includeItemsWithQuantityZero' => 'false');
$data_string = json_encode($data);
$context = stream_context_create(array(
'http' => array(
'method' => "POST",
'header' => "Accept: application/json\r\n".
"Content-Type: application/json\r\n",
'content' => $data_string
)
));
$result = file_get_contents('https://user.traxia.com/app/api/inventory', false, $context);
$jsonData = $result;
$phpArray = json_decode($jsonData, true);
$phpArray = $phpArray['results'];
$activeonly = array_filter($phpArray, function($active) { return $status['status']=="ACTIVE"; });
$mykeys = array('name','sku','category','color','size','currentPrice');
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/test/css/search-results.css">
<script type="text/javascript" src="/test/js/tablesorter/jquery-latest.js"></script>
<script type="text/javascript" src="/test/js/tablesorter/jquery.tablesorter.js"></script>
<script>
$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
</script>
</head>
<div class="CSSTableGenerator">
<table id="myTable" class="tablesorter">
<thead>
<tr>
<?php
foreach($mykeys as $k) {
if ($k == "name") {
$k = "Name";
}
if ($k == "sku") {
$k = "SKU";
}
if ($k == "category") {
$k = "Category";
}
if ($k == "color") {
$k = "Color";
}
if ($k == "size") {
$k = "Size";
}
if ($k == "currentPrice") {
$k = "Price";
}
echo "<th style='cursor:pointer'>$k<img src='/test/images/UpDown.png' width='8px' height='auto' style='margin: 0px 20px'></th>";
}
?>
</tr>
</thead>
<tbody>
<?php
foreach($phpArray as $key => $values) {
echo '<tr>';
foreach($mykeys as $k) {
if ($values['category'] == 'UNCATEGORIZED') continue;
$value = $k == "currentPrice" ? '$' . number_format($values[$k]/100,'2') : $values[$k];
echo "<td>" . $value . "</td>";
}
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</html>
So basically I need to combine these two files while not running the second file until the search form has been submitted. Thanks!
Yes .. you can load with Javscript into a DIV on the page with search variables. This example has a login form, but the idea is the same. Form fields, a submitted form, etc.. I include a "please wait" loading message as well. This is designed this way because i have mutiple forms on the same page and i call the function to submit them seperately with the "formName" and "message" variables of the function.
function loader(message) {
if (message == "" || message == null) {
message = "Please wait ...";
}
$('#DivWhereYouWantData').html('<div style="width:100%;text-align:center;margin-top:150px;"><div style="font-size:20px;"><b>' + message + '</b></div></div>');
}
function submitForm(formName,message) {
$.ajax({
data: $("#" + formName).serialize(),
type: $("#" + formName).attr('method'),
url: $("#" + formName).attr('action'),
beforeSend: function() {
loader(message);
},
success: function(response) {
$('#DivWhereYouWantData').html(response);
}
});
return false;
}
and the jQuery in the header -
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
and the HTML to go along with the scripts -
<form id="login" name="login" method="post" action="processLogin.php" onsubmit="return submitForm('login','Logging you in ...');">
Logn: <input type="text" style="text-input" name="login" id="login" />
Password: <input type="password" style="text-input" id="password" name="password" />
<input style="background:none; border:none; padding:0; height:auto; width:auto;" type="image" src="img/signIn.png" />
</form>
<div id="DivWhereYouWantData">
<!-- Dynamic content loads here -->
</div>
$("button").click(function(){
$.ajax({
url:"results.php",
success:function(result){
$("#div1").html(result);
}
});
});`
just use Jquery Ajax its the better way to do this and
check out thsi link try the second answer it is too simple jQuery Ajax POST example with PHP
I want to key down my search results and for this i am using this jquery below:
$('#ChangeAccountInput').keydown(function(e)
{
if(e.keyCode==40)
{
$('#results').css("background-color", "yellow");
}
});
But the problem is, it is applying to the full div not on a single value.
Above jquery applying to all like:
html:
<input id='ChangeAccountInput' class="InputBorder" placeholder="Search" style="display: none; margin-top: -79px; margin-left: -226px; border: 1px solid rgb(133, 133, 133); font-family: calibri; font-size: 15px; color: rgb(68, 68, 68); padding-left: 6px; padding-right: 21px; width: 182px"/>
<i class="icon-search" id="iconsearch1" style="display: none; margin-top: -37px; margin-left: -22px;"></i>
<div id="results" stlye='display: none'></div>
php:
while($row = oci_fetch_assoc($query))
{
echo "<a href='#'>";
echo '<font>'.$row['ACCOUNT_TYPE'].'</font>';
echo '<br>';
echo "<div style='border: 1px solid #AAAAAA; margin-left: -4px'></div>";
echo "</a>";
}
ajax:
$.ajax
({
type: 'GET',
url: 'Reports/Account Search.php',
data: 'GetAccountInput='+GetAccountInput,
success: function(data)
{
$('#results').html(data);
$('#results').show();
}
});
Account Search File:
<?php
error_reporting(0);
$user = "fyp";
$pass = "fyp";
$host = "localhost/CRMP";
// Connection with the Oracle.
$con = oci_connect($user, $pass, $host);
// If connection is established with the Oracle or not.
if (!$con)
{
//header('location:../../../Extra/Error_Other.php');
}
else
{
//echo "Connected to Oracle.";
}
?>
<?php
$GetAccount = $_GET['GetAccountInput'];
if($GetAccount != '')
{
$query = oci_parse($con, "SELECT DISTINCT ACCOUNT_TYPE FROM ACCOUNTS WHERE ACCOUNT_TYPE LIKE '%".$GetAccount."%'");
oci_execute($query);
$check = oci_fetch_array($query);
if(empty($check))
{
echo "<a href='#'>";
echo "No Result Found";
echo "</a>";
}
while($row = oci_fetch_assoc($query))
{
echo "<a>";
echo $row['ACCOUNT_TYPE'];
echo '<br>';
echo "</a>";
echo "<div style='border: 1px solid #777A79; margin-left: -6px'></div>";
}
}
else
{
}
?>
Help would be apprciated.
I thought about this some more and I came up with a solution that will work for you. All you should have to do is add the kind of styling that you want and other animations as needed.
http://jsfiddle.net/2wk6Q/1095/
$('#ChangeAccountInput').keydown(function (e) { //not actually the down key though :-)
if ($('a').hasClass('yellowBack')) { // do any links have this class?
var selected = $('a.yellowBack'); // if the do, they are the 'selected' link
selected.removeClass('yellowBack'); // this cleans up the one that we move from
if (40 == e.keyCode) { // going down the list
if (selected.next().length == 0) {
// if there isn't another list item, highlight the first
$('#results a:first').addClass('yellowBack');
} else {
// add the class to the next item
selected.next().addClass('yellowBack');
}
} else { // going up the list
if (selected.prev().length == 0) {
// add the class to the last item if you have gone to the top of the list
$("#results a:last").addClass("yellowBack");
} else {
// add the class to the next one up the list
selected.prev().addClass('yellowBack');
}
}
} else {
// if none were initially selected, select the first one
$("#results a:first").addClass("yellowBack");
}
});
This will allow you to move up and down the returned list, no matter what length the list is. Proper styling will prevent scrollbar issues that you mentioned above.
EDIT: modifying PHP so that output matches latest fiddle -
while($row = oci_fetch_assoc($query))
{
echo "<div style='border-bottom: 2px solid #777A79; margin-left: -4px'>";
echo "<a href='#'>";
echo '<font>'.$row['ACCOUNT_TYPE'].'</font>';
echo "</a>";
echo "</div>";
}
The reason for the modification is because the PHP is essentially outputting HTML that is hard to work with in JavaScript. The OP is learning how to format ALL of his code, from back to front, so that it plays nicely together.
I'm stuck with my codes for 2 weeks already. I want to have a page with 2 dropdowns. The first DD will show all 'states' from my database and the second DD should be based on the 1st DD's value. I think my codes are OK but the problem is the integration with wordpress itself. Is there any codes/functions/etc needed for a page to be read as ajax?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>None</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function parseResponse(adminResponse,nList){
var nText = adminResponse.getElementsByTagName('optionText');
var nVal = adminResponse.getElementsByTagName('optionVal');
nList.options.length = 1;
for (i=0; i<nText.length; i++)
{
var nOption = document.createElement('option');
nOption.appendChild(document.createTextNode(nText[i].firstChild.data));
nOption.value = nVal[i].firstChild.data;
nList.appendChild(nOption);
}
}
function update(nVal,nList,getFile){
var adminRequest = window.XMLHttpRequest ? new XMLHttpRequest()
: window.ActiveXObject
? new ActiveXObject("Microsoft.XMLHTTP")
: null;
adminRequest.onreadystatechange = function()
{
if (adminRequest.readyState == 4)
{
if (adminRequest.status == 200)
{
var adminResponse = adminRequest.responseXML;
parseResponse(adminResponse,nList);
}
else {
alert('Error ' + getFile + ' --- ' + adminRequest.statusText);
}
}
}
var infoStr = "?choice="+nVal;
adminRequest.open("GET", getFile + infoStr, true);
adminRequest.send(null);
}
function init(){
var nForm = document.forms[0];
nForm['state'].onchange = function()
{
if (this.value != "")
{
update(this.value,nForm['city'],'<?php echo get_template_directory_uri(); ?>/updateGroup.php');
}
}
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
<style type="text/css">
body {background-color: #eae3c6; margin-top: 60px;}
form {width: 430px; margin: auto;}
fieldset {width: 410px; background-color: #f0fff0; border: 1px solid #87ceeb;}
legend {font-family: times; font-size: 14pt; color: #00008b; background-color: #87ceeb;
padding-left: 3px; padding-right: 3px ; margin-bottom:5px;}
select {font-family: tahoma; font-size: 10pt; width: 160px; margin-left: 35px; margin-bottom: 10px;}
</style>
</head><?php /* Template Name: Practice */
?>
<body>
<?php
global $wpdb;
$query = "SELECT * FROM zipcode GROUP BY FULLSTATE ASC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$dd .= "<option value='".$row['STATE']."'>".$row['FULLSTATE']."</option>";
}
?>
<form action="">
<fieldset>
<legend>Form</legend>
<select name="state">
<option value="">Select State</option>
<?php echo $dd; ?>
</select>
<select name="city" onchange="alert(this.value)">
<option value=""> Make a selection </option>
</select>
</fieldset>
</form>
</body>
</html>
First, I pasted those codes in notepad++ and saved it as practice.php. Uploaded it to my wordpress theme directory. Typing http://www.site.com/practice.php shows 'page not found' so i went to wordpress dashboard and created a new page -> assigned the template named 'practice'. typed http://www.site.com/practice.php again and it works.
<?php
$choice = $_GET['choice'];
$xml = "<?xml version='1.0' ?><options>";
global $wpdb;
$query = "SELECT * FROM zipcode WHERE STATE = '$choice'";
$result = #mysql_query($query);
$num = #mysql_num_rows($result);
if ($result && $num > 0)
{
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$xml .= "<optionText>" . $row['CITY'] . "</optionText><optionVal>" . $row['CITY'] . "</optionVal>";
}
}
$xml .= "</options>";
#mysql_free_result($result);
#mysql_close();
header("Content-Type: text/xml");
echo $xml;
?>
Ok so next i created a page with the codes above and named it updateGroup.php. uploaded it on wordpress theme directory.
Tested my codes and...I can't get it to work!! :(
Please i need help. should i add get_header and get_footer for my reference page? or do i need to configure something in wordpress to recognize my ajax?