Keeping page in one place while changing images or reloading page? - javascript

I've checked this site for the same kind of questions but I'm not looking to change the image on this project without the page reloading - it needs to reload. Although when I do click the next or previous buttons the page jumps right to the top again as it should do, is there a way to combat that so that when the user clicks the next image the page reloads with the image on screen rather than the user having to scroll down every time? Here is my script:
$albumName = "Our Gallery"; // Name your album!
/*
* Installation:
* 1.) Place your photos into the images directory.
* - Photos will be displayed in alphabetical order.
* 2.) Rename the "basic-php-photo-album" folder to anything you wish.
* - Example: paris-photo-album
* 3.) Upload the renamed folder and all of its contents to your server.
*
* That's it! Make multiple albums by repeating the above 3 steps.
*/
/*
* You shouldn't need to change anything beyond this.
*
*/
$p = $_GET['p'];
if ($handle = opendir("uploads")) {
$i = 1;
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$img[$i] = $file;
if ($p == $img[$i]) {
$ci = $i;
}
$i++;
}
}
closedir($handle);
$ti = $i - 1;
$pi = $ci - 1;
if ($p == "") {
$ni = $ci + 2;
} else {
$ni = $ci + 1;
}
$prevNext = "";
if ($pi > 0) {
$piFile = $img[$pi];
$prevNext .= "Previous &#171";
} else {
$prevNext .= "«";
}
$prevNext .= " | ";
if ($ni <= $ti) {
$niFile = $img[$ni];
$prevNext .= "&#187 Next";
} else {
$prevNext .= "»";
}
if ($p == "") {
$p = $img[1];
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Dave's Caravan Lettings</title>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="Hire our Deluxe Plus Caravan based in Sandy Bay, Exmouth for an easy, great priced family holiday! Comes complete with all required facilities as standard!">
<meta name="keywords" content="Haven,Holidays,Sandy,Bay,Devon,Cliffs,Exmouth,Beach,Caravan,Hire,Rental,Rent,Cheap,Holiday,Family,Entertainment,Daves,Letting,Lettings,Fun,Best,Stay,Nights,Price,Buy">
<meta name="author" content="BaseEnterprises WebDesign">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="imagetoolbar" content="no">
<style type="text/css">
td, select, input {
font-family: arial, helvetica, sans-serif;
font-size: 11px;
}
.hRule {
border-top: 1px solid #cdcdcd;
margin: 0px 0px 10px 0px;
}
img {
border: 1px solid #333333;
}
.nextPrevious {
font-size: 18px;
color: #cdcdcd;
padding-bottom: 15px;
}
a, a:visited {
color: #cc0000;
text-decoration: none;
}
a:active, a:hover {
color: #cc0000;
text-decoration: underline;
}
</style>
<link href='http://fonts.googleapis.com/css?family=Rochester' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.3";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="header-bg">
<div class="wrap">
<div class="header">
<div class="logo">
<h1>Dave's Caravan Lettings</h1>
</div>
</div>
<div class="header-bot">
<div class="menu">
<ul>
<li class="home">Home</li>
<li class="">Location</li>
<li class="">Facilities</li>
<li class="">Availability</li>
<li class="">Contact Us</li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
<div class="banner">
<div class="wrap">
<span class="banner-img">
<img src="images/banner2.jpg" alt=""/>
</span>
</div>
</div>
</div>
<div class="main">
<div class="wrap">
<div class="content-bot">
<h3><?php echo $albumName; ?></h3>
<p>Images sent to us by previous holiday makers staying in our Caravan... See what it's like yourself by browsing the images below...</p><br></br>
<div class="inner-top">
<div class="section group" align="center">
<div class="hRule"></div>
<table border="0" cellpadding="0" cellspacing="0" align="center">
<tr align="center">
<td class="nextPrevious"><?php echo $prevNext; ?></td>
</tr>
<tr align="center">
<td><img src="uploads/<?php echo $p; ?>" alt="<?php echo $$albumName; ?>" border="0" height="300px" width="400px"></td>
</tr>
</table>
</div>
</div>
<div class="clear"></div>
</div>

If you wanted to scroll right to the bottom automatically, depending on how large your images are - you could use something like this:
$(".section group").animate({ scrollTop: $(document).height() }, "fast");
return false;
And then add this to your page:
<div class="section group" align="center" style="overflow-y: scroll;height:520px;width:520px 240px">
Then all you would do is fiddle around with the width and height attributes until they match your design.

JavaScript
get the current scroll with:
document.documentElement.scrollTop + document.body.scrollTop
And add that to the reloaded page so it scrolls to the same position as it was.

I would try to pass the scroll position over to the next page, and restore that setting with javascript. My example includes jQuery to make life easier. Plain Javascript would probably involve some cross browser compatibility hassle.
You could insert this (tested) example code in your <head> section:
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function() {
// set scroll position to the previous state, only if it was given
<?php if( isset($_GET['scrollTop']) ) {
echo "$('body').scrollTop(" . $_GET['scrollTop'] . ");";
} ?>
// append current scroll position parameter to the link
$('.nextPrevious').on('click', 'a', function(e) {
e.preventDefault();
document.location.href = $(this).attr('href') + '&scrollTop=' + $('body').scrollTop();
});
});
</script>
If you are already using jQuery in your page you don't need to include it again, of course.

Related

After adding a non-case sensitive search and clickable pictures, script stopped working

Trying to make my first project with bunch of pictures, with a filter/search bar at the top that would filter the pictures depending on the input. For example if the input would be "Aatrox", it would show "Aatrox" and not "Jayce" and or "Senna" and so on. Script was working fine, I added a .toLowerCase() so its not case sensitive and then I added to the pictures so they are clickable and each lead to their own page. After adding these two the search bar stopped working.
Here is the snippet of the script
<script>
function search(){
var searchText = (document.getElementById("searchInput").value).toLowerCase();
var images = document.querySelectorAll(".image_container > img");
if(searchText.length > 0){
images.forEach((image) => {
image.classList.add("hide");
if((image.dataset.tags).toLowerCase().indexOf(searchText) > -1){
image.classList.remove("hide");
}
});
}else{
images.forEach((image) => {
image.classList.remove("hide");
});
}
}
</script>
Here is the HTML part
<head>
<title> Counterpicks </title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1> Counterpicks pro debily </h1>
<div class="container">
<div class="searchbox_container">
<div class="searchbox">
<input type="text" name=" " placeholder="Search" class="search" id="searchInput" onkeyup="search()">
</div>
</div>
<div class="image_container">
<img data-tags="aatrox" src="aatrox.webp" alt="Aatrox" class="actionimages">
<img data-tags="ahri" src="ahri.webp" alt="Ahri" class="actionimages">
</div>
I input only few of the lines because they are just repeating for 130 lines.
And here is the CSS
.container {
background: rgba(0,0,0,0);
text-align: center;
margin-left: 20%;
margin-right: 20%;
}
.searchbox {
text-align: center;
margin-left: 20%;
margin-right: 20%;
margin-bottom: 20px;
}
.image_container {
clear:both;
}
.hide {
display:none;
This is my first project with JavaScript so I will be happy for any constructive criticism.
Replace:
var images = document.querySelectorAll(".image_container > img");
with:
var images = document.querySelectorAll(".image_container > a > img");

JS Problems by displaying fetched MySQL data in 2 different div boxes [PHP, MySQL & JS]

I'm learning JS (without JQuery for now!) and got a problem with my code and need your help!
I'm working on a code which fetch the image title out of a database and put it in a kinda list.
If the user clicks on the title, a other div box pops up and shows the image describtion.
My Problem is that my code only display the first "img_descr" in each popup box.
And because the "img_title" list is dynamically (it depends on what the user types in the search bar) it makes it even more a bit difficult.
Below I will paste a simple version of my code with php code and below that i will past a snippet. (by clicking on the "play" button you can see a simulation of my code).
Click on each title and you will see, only 1 describtion will show up for each title.
▽ Here you can see a simple version of my code with PHP code ▽
<!DOCTYPE html>
<html>
<head>
<title>XY</title>
<meta charset="UTF-8"/>
</head>
<body>
<div id="frame">
<?php
$db = mysqli_connect("localhost", "root", "", "xy");
$result = mysqli_query($db, "SELECT * FROM images");
while ($row = mysqli_fetch_array($result))
{
echo "<div class='click_box'>";
echo "<a class='img_id'>ID: ".$row['img_id']."</a><br>";
echo "<div class='img_title'><a>Title: <b>".$row['img_title']."</b></a></div>";
echo "</div>";
echo "<div id='popup'>";
echo "<div class='img_descr'><a>Descr: <b>".$row['img_descr']."</b></a></div>";
echo "</div>";
}
?>
</div>
<style>
*{
font-family: arial;
padding: 0px;
margin: 0px;
}
body{
background-color:rgba(100,100,100);
}
.click_box{
height: 50px;
width: 150px;
background-color:rgba(150,150,150);
margin-top: 10px;
margin-left: 10px;
}
.img_id{
color:rgba(100,100,100);
}
.img_title{
color: white;
}
.img_title:hover{
cursor: pointer;
color:rgba(50,50,50);
}
#popup{
position: absolute;
height: 230px;
width: 350px;
top: 10px;
left: 170px;
background-color:rgba(50,50,50);
opacity: 0;
}
.img_descr{
color: white;
}
</style>
<script>
let myarray = Array.from(document.querySelectorAll('.img_title'))
let bg = document.getElementById('popup');
myarray.map((e) => {
e.addEventListener("click", e=>{
// retrieve the actual value of opacity for bg
bgStyle = window.getComputedStyle(bg, null).getPropertyValue("opacity");
// if the opacity is "0" make it "1" otherwhise make it "0"
let opacity = bgStyle == "0" ? "1" : 0;
// use the opacity variable
bg.setAttribute("style", `opacity:${opacity};`);
})
})
</script>
</body>
</html>
▽ Here you can see a snippet i created, but without PHP code ▽
there you can see, only the first "img_descr" do work!
let myarray = Array.from(document.querySelectorAll('.img_title'))
let bg = document.getElementById('popup');
myarray.map((e) => {
e.addEventListener("click", e=>{
// retrieve the actual value of opacity for bg
bgStyle = window.getComputedStyle(bg, null).getPropertyValue("opacity");
// if the opacity is "0" make it "1" otherwhise make it "0"
let opacity = bgStyle == "0" ? "1" : 0;
// use the opacity variable
bg.setAttribute("style", `opacity:${opacity};`);
})
})
*{
font-family: arial;
padding: 0px;
margin: 0px;
}
body{
background-color:rgba(100,100,100);
}
.click_box{
height: 50px;
width: 150px;
background-color:rgba(150,150,150);
margin-top: 10px;
margin-left: 10px;
}
.img_id{
color:rgba(100,100,100);
}
.img_title{
color: white;
}
.img_title:hover{
cursor: pointer;
color:rgba(50,50,50);
}
#popup{
position: absolute;
height: 230px;
width: 350px;
top: 10px;
left: 170px;
background-color:rgba(50,50,50);
opacity: 0;
}
.img_descr{
color: white;
}
<!DOCTYPE html>
<html>
<head>
<title>XY</title>
<meta charset="UTF-8"/>
</head>
<body>
<div id="frame">
<div class='click_box'>
<a class='img_id'>ID: 1</a><br>
<div class='img_title'><a>Title: <b>Golden Retriever</b></a></div>
</div>
<div id='popup'>
<div class='img_descr'><a>Descr: <b>UK:DFYDFBAERSDFBYDFBYDFydfbydfBaeydfb1311y</b></a></div>
</div>
<div class='click_box'>
<a class='img_id'>ID: 2</a><br>
<div class='img_title'><a>Title: <b>Appenzeller Sennenhund</b></a></div>
</div>
<div id='popup'>
<div class='img_descr'><a>Descr: <b>Swiss:erydfydfbrehaydydfbydfydbaerydf2ydfb</b></a></div>
</div>
<div class='click_box'>
<a class='img_id'>ID: 3</a><br>
<div class='img_title'><a>Title: <b>German Shepard</b></a></div>
</div>
<div id='popup'>
<div class='img_descr'><a>Descr: <b>Germany:ydf3d1fby3df1by3dfb6ydfb31ydf31ydf</b></a></div>
</div>
<div class='click_box'>
<a class='img_id'>ID: 4</a><br>
<div class='img_title'><a>Title: <b>Alaskan Klee Kai</b></a></div>
</div>
<div id='popup'>
<div class='img_descr'><a>Descr: <b>USA:f3ngxfgxfgnxfxfgnxfg3xf31gnxfgner6ae13</b></a></div>
</div>
</div>
</body>
</html>
It seems it have to do something with the "id="popup"... and if i change the popup div from "id" to "class", change "document.getElementById" to "document.getElementsByClassName" and change the css "#popup" to ".popup", nothing work then.
If you would make it totally different, please let me know. (i'm a js beginner)
first of all, you have to replace the multiple popup ids with classes (in css and html)
Here is the js code with the corrections.
let myarray = Array.from(document.querySelectorAll('.click_box'));
myarray.map((e) => {
e.addEventListener("click", event => {
let popups = Array.from(document.querySelectorAll('.popup'));
popups.map((popup) => {
popup.setAttribute("style", 'opacity:0');
})
let bg = e.nextElementSibling;
bg.setAttribute("style", 'opacity:1');
})
})
here is the process :
get the click boxes (notice that I use .click_box as my click target)
get all popups and hide them using opacity: 0
get the element after the clicked one using nextElementSibling. as the click event is on clickBox, the next element will be the popup
show the popup using opacity: 1
jsfiddle here : https://jsfiddle.net/1L0ehpuy/18/
warning : this code depends on the html markup to work properly : you have to keep the popup right after the click_box element otherwise the nextElementSibling won't be the popup
here is the php code with classes instead of ids. with this php code and the js above, everything should be fine
<?php
$db = mysqli_connect("localhost", "root", "", "xy");
$result = mysqli_query($db, "SELECT * FROM images");
while ($row = mysqli_fetch_array($result)) {
echo "<div class='click_box'>";
echo "<a class='img_id'>ID: ".$row['img_id']."</a><br>";
echo "<div class='img_title'><a>Title: <b>".$row['img_title']."</b></a></div>";
echo "</div>";
echo "<div class='popup'>";
echo "<div class='img_descr'><a>Descr: <b>".$row['img_descr']."</b></a></div>";
echo "</div>";
}
?>
new version to hide the popup on 2nd click
let myarray = Array.from(document.querySelectorAll('.click_box'));
myarray.map((e) => {
e.addEventListener("click", event => {
let bg = e.nextElementSibling;
if (bg.style.opacity == 1) {
bg.setAttribute("style", 'opacity:0');
} else {
let popups = Array.from(document.querySelectorAll('.popup'));
popups.map((popup) => {
popup.setAttribute("style", 'opacity:0');
})
bg.setAttribute("style", 'opacity:1');
}
})
})
there are not many changes : at the begining of the function, I just added a if to check if the related popup is already shown. if so, I hide it.
fiddle here : https://jsfiddle.net/1L0ehpuy/21/
This is new, edited version of my code. I've transfered every jQuery code into pure JavaScript. I've also tried to comment my JS code so it will be easier for you to understand it.
//Pass the clicked element in function 'openPopup' and name it as 'el'
//We are passing the clicked element from the HTML, you can see it at "onclick='openPopup(this)'"
//The word 'this' is a variable for current element
function openPopup(el){
var parent = el.parentElement;
var child = null;
//Loop through children of parent element
for (var i = 0; i <= parent.childNodes.length; i++) {
//Only if children has class, check if children's class contains 'popup'
if(parent.childNodes[i].classList){
if (parent.childNodes[i].classList.contains("popup")) {
//If we have the popup element, add it to a variable 'child'
child = parent.childNodes[i];
break;
}
}
}
//If assigned popup is opened
if(child.classList.contains("visible")){
//Remove class 'visible' from the popup element (popup is stored in 'child' variable)
child.classList.remove("visible");
} else {
//Close all popups by removing class 'visible' from all popups
var popups = document.getElementsByClassName("popup");
for (var i = 0; i < popups.length; i++) {
popups[i].classList.remove("visible");
}
//Add class 'visible' to popup assigned to our button (still stored in 'child' variable)
child.classList.add("visible");
}
}
*{
font-family: arial;
padding: 0px;
margin: 0px;
}
body{
background-color:rgba(100,100,100);
}
.click_box{
height: 50px;
width: 150px;
background-color:rgba(150,150,150);
margin-top: 10px;
margin-left: 10px;
}
.img_id{
color:rgba(100,100,100);
}
.img_title{
color: white;
}
.img_title:hover{
cursor: pointer;
color:rgba(50,50,50);
}
.popup{
position: absolute;
height: 230px;
width: 350px;
top: 10px;
left: 170px;
background-color:rgba(50,50,50);
display: none;
}
.popup.visible{
display: block;
}
.img_descr{
color: white;
}
<!DOCTYPE html>
<html>
<head>
<title>XY</title>
<meta charset="UTF-8"/>
</head>
<body>
<div id="frame">
<div class="frame__wrapper">
<div class='click_box' onclick='openPopup(this)'>
<a class='img_id'>ID: 1</a><br>
<div class='img_title'><a>Title: <b>Title 1</b></a></div>
</div>
<div class='popup'>
<div class='img_descr'><a>Descr: <b>Desc 1</b></a></div>
</div>
</div>
<div class="frame__wrapper">
<div class='click_box' onclick='openPopup(this)'>
<a class='img_id'>ID: 2</a><br>
<div class='img_title'><a>Title: <b>Title 2</b></a></div>
</div>
<div class='popup'>
<div class='img_descr'><a>Descr: <b>Desc 2</b></a></div>
</div>
</div>
<div class="frame__wrapper">
<div class='click_box' onclick='openPopup(this)'>
<a class='img_id'>ID: 3</a><br>
<div class='img_title'><a>Title: <b>Title 3</b></a></div>
</div>
<div class='popup'>
<div class='img_descr'><a>Descr: <b>Desc 3</b></a></div>
</div>
</div>
<div class="frame__wrapper">
<div class='click_box' onclick='openPopup(this)'>
<a class='img_id'>ID: 4</a><br>
<div class='img_title'><a>Title: <b>Title 4</b></a></div>
</div>
<div class='popup'>
<div class='img_descr'><a>Descr: <b>Desc 4</b></a></div>
</div>
</div>
</div>
</body>
</html>

Bootstrap progress bar colour change according to width value dynamically

I have created a progress bar. Value is being fetched from database. Now i want to categorize the colour of progress bar like if width value is below 50 so progress bar colour is red. If value is above 50 and below 90 colour is blue if value is 100 then colour is green.
progress bar is display in table cell. and values are fetched from database
<tr class="success">
<td><?php echo "$row->ID"; ?></td>
<td><?php echo "$row->name"; ?></td>
<td><div class="progress" style = "height:24px;width:200px">
<div class="progress-bar" id = "newprogress" role="progressbar" aria-valuenow="<?php echo "$row->Percentage"; ?>" style = "width :<?php echo "$row->Percentage"; ?>%";>
<?php echo "$row->Percentage" ?>%
</div>
</div>
<td>
as i have tried one of the solution here
$(document).ready(function(){
var bar = parseInt($("#newprogress").width());
if (bar >= 90) {
$("#newprogress").removeClass("bckColor").addClass("bar-success");
}
else if (bar >= 50 && bar < 90) {
$("#newprogress").removeClass("bar-success").addClass("bckColor");
}
});
I think you selected the wrong element.
$(document).ready(function() {
var bars = $('.progress-bar');
for (i = 0; i < bars.length; i++) {
console.log(i);
var progress = $(bars[i]).attr('aria-valuenow');
$(bars[i]).width(progress + '%');
if (progress >= "90") {
$(bars[i]).addClass("bar-success");
} else if (progress >= "50" && progress < "90") {
$(bars[i]).addClass("bar-warning");
} else {
$(bars[i]).addClass("bar-error");
}
}
});
.progress {
width: 200px;
height: 24px;
border-radius: 10px;
background-color: #F1F1F1;
margin-bottom: 10px;
}
.progress-bar {
border-radius: 10px;
height: 24px;
display: block;
}
.bar-warning {
background-color: yellow;
}
.bar-success {
background-color: green;
}
.bar-error {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress" style="heigt:24px;width:200px">
<div class="progress-bar" name="progress" role="progressbar" aria-valuenow="90"></div>
</div>
<div class="progress" style="heigt:24px;width:200px">
<div class="progress-bar" name="progress" role="progressbar" aria-valuenow="30"></div>
</div>
<div class="progress" style="heigt:24px;width:200px">
<div class="progress-bar" name="progress" role="progressbar" aria-valuenow="50"></div>
</div>
Try below code.
$(document).ready(function(){
var bar = parseInt($('.progress').width());
if (bar >= 90){
$(".progress").removeClass("bckColor").addClass("success");
}
else if (bar >= 50){
$(".progress").removeClass("success").addClass("bckColor");
}
});
.bckColor {
background-color: blue !important;
}
.success {
background-color: green !important;
}
Use the Below code I have named sample.php
Here the value will be collected from the another file data.php and changes the color according to the condition provided
Languages Used: HTML,PHP, JS
sample.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<?php require_once('data.php'); ?>
<script>
var myVar = setInterval(inter, 1000);
function inter() {
document.getElementById("boot").style.width =
<?php echo $x; ?>+"%";
document.getElementById("boot").innerHTML =
<?php echo $x; ?>+"%";
if (
<?php echo $x; ?>< 90)
{
document.getElementById("boot").className = "progress-bar progress-bar-danger";
}
else
{
document.getElementById("boot").className = "progress-bar progress-bar-success";
}
}
</script>
</head>
<body>
<table>
<td>
<div class="progress" style = "height:24px;width:200px">
<div name="progress" role="progressbar" id="boot" aria-valuenow="
<?php echo'$row->Percentage';?>" >
</div>
</div>
</td>
</table>
</body>
</html>
Here is data.php
Results:
I realise you were asking for a JavaScript solution, but this can be achieved (somewhat) in PHP.
You are already working with variables in the PHP script to set values for your HTML output, so why not do the same for the colour of your progress bar?
This example uses the default Bootstrap colours, but you can substitute others if you require:
// Value retrieved from the database. This can be a percentage (which may be easier
// to work with or just use the raw value depending on your needs)
$valueFromDatabase = 9;
// This will give us a green bar, 9% wide.
// Use the switch command to set the output colour (using the Bootstrap
// default colours Primary, Warning, Danger, Success etc. Set these as you need.
switch ($valueFromDatabase) {
case ($valueFromDatabase <= 10):
$bar_colour = "success";
break;
case (($valueFromDatabase > 10) && ($valueFromDatabase <= 30)):
$bar_colour = "warning";
break;
case ($valueFromDatabase > 30):
$bar_colour = "danger";
break;
}
// Now we use $bar_colour to set the colour in the output below.
// Width set to the value retrieved from the database
echo "<div class='row'>\n
<div class='col-md-12'>\n
<h4>Your Progress Bar</h4>\n
<div class='progress md-progress pos-rel' style='height:25px'>\n
<div class='progress-bar progress-bar-$bar_colour progress-bar-striped' style='width:$valueFromDatabase%; height: 25px'>
<span style='line-height: 25px'>$valueFromDatabase%</span>
</div>\n
</div>\n
</div>\n
</div>\n";

Auto-Suggest Text Box

I found an example online that shows how to build a auto-suggest text field by using javascript and PHP. Originally I started out by building my on version of the example, but after many failed attempts in getting it to work, I decided to see if the example itself even worked. I copied and pasted the example, changing only the database connection and the information regarding the database table. To my surprise the example still doesn't work! In my database I have a a table called Device and in that table there are three columns, ID,Device_type, and Price. Right now I have one value in the table and it's Apple iPhone 6 in the Device_type column, so when the program is working correctly, it should start to auto suggest Apple iPhone 6 as soon as I type "A" into the text box. Unfortunately, that doesn't happen, a dropdown box appears, as it should, but the box is blank and doesn't show any suggestions.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Suggestion Example</title>
<style type="text/css">
<!--
div.suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
text-align: left;
}
-->
</style>
<script type="text/javascript">
var nameArray = null;
</script>
</head>
<body onclick="document.getElementById('divSuggestions').style.visibility='hidden'">
<?php
mysql_connect("hostname", "username", "password") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DeviceRecycling');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo("<script type='text/javascript'>");
echo("this.nameArray = new Array();");
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
<!-- --------------------- Input Box --------------------- -->
<table border="0" cellpadding="0" width="50%" align="center">
<tbody align="center">
<tr align="center">
<td align="left">
<input type="text" id="txtSearch" name="txtSearch" value="" style="width: 50%; margin-top: 150px; background-color: purple; color: white; height: 50px; padding-left: 10px; padding-right: 5px; font-size: larger;" onkeyup="doSuggestionBox(this.value);" />
<input type="button" value="Google It!" name="btnGoogleIt" style="margin-top: 150px; background-color: purple; color: white; height: 50px; font-size: larger;" onclick="window.location='http://www.google.com/#hl=en&source=hp&q=' + document.getElementById('txtSearch').value" />
</td>
</tr>
<tr align="center">
<td align="left">
<div class="suggestions" id="divSuggestions" style="visibility: hidden; width: 50%; margin-top: -1px; background-color: purple; color: white; height: 250px; padding-left: 10px; padding-right: 5px; font-size: larger;" >
</div>
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function doSuggestionBox(text) { // function that takes the text box's inputted text as an argument
var input = text; // store inputed text as variable for later manipulation
// determine whether to display suggestion box or not
if (input == "") {
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
} else {
document.getElementById('divSuggestions').style.visibility = 'visible'; // shows the suggestion box
doSuggestions(text);
}
}
function outClick() {
document.getElementById('divSuggestions').style.visibility = 'hidden';
}
function doSelection(text) {
var selection = text;
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
document.getElementById("txtSearch").value = selection;
}
function changeBG(obj) {
element = document.getElementById(obj);
oldColor = element.style.backgroundColor;
if (oldColor == "purple" || oldColor == "") {
element.style.background = "white";
element.style.color = "purple";
element.style.cursor = "pointer";
} else {
element.style.background = "purple";
element.style.color = "white";
element.style.cursor = "default";
}
}
function doSuggestions(text) {
var input = text;
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
</script>
</body>
</html>
In my attempt to trouble shoot, I have discovered a few things. First off the connection string to the database is good, and that is not the problem. In an attempt to further check whether it was the database query that was causing issues, I have discovered that if I remove the echo("<script type='text/javascript'>") from the PHP portion of the code, that it will actually print Apple iPhone 6 at the top of the page, which tells me the query itself is actually working. Obviously though, by removing the javascript tag the program still doesn't work because it should only be displaying the results as you type something that matches what is in the database.
hi maybe you have a error on your code
this is a little example
for get the result and show
autocomplete.php
<?php
$connection = mysqli_connect("localhost","username","password","employee") or die("Error " . mysqli_error($connection));
//fetch department names from the department table
$sql = "select department_name from department";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['department_name'];
}
echo json_encode($dname_list);
?>
for view and show the result
demo.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<!-- load jquery ui css-->
<link href="path/to/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<!-- load jquery library -->
<script src="path/to/jquery-1.10.2.js"></script>
<!-- load jquery ui js file -->
<script src="path/to/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#department_name").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="department_name" type="text" size="50" />
</body>
</html>
i preffer use jquery
donwload jquery
enter link description here
result

how to create 3 columns landscape layout

i'm fighting with 3 columns landscape layout
i would like to print a page with 3 same fix with columns (unfortunately height are not the same, sometimes pages will break down to 2 pages)
what i would like to get in landscape is:
and what i'm getting is:
i cannot position this like it should be
can you advise me for some good solution for this crap please
any advice will be helpful, or maybe you whose already struggling with this problem and you can give my god direction please
i who's doing this not in landscape a few days ago and it whose working find
i didn't find a solution in web for this now
this is my starting code:
<?php
include("bd.php");
$print[] = null;
if(isset($_GET['option1'])) {
$print = $_GET['option1'];
}
$integerIDs = array_map('intval', explode(',', $print));
$usersIDS = implode(',', $integerIDs);
$requete = "SELECT p.pr_id as id, p.pr_nom as nom, p.pr_poids as poids, p.pr_ingredients as ingredients, p.pr_description as description, p.pr_valeurs_energetiques as valeurs_energetiques, p.pr_valeurs_nutritionnelles as valeurs_nutritionnelles, c.ca_nom as categorie, sc.sc_nom as sous_categorie, p.pr_enligne as enligne FROM produit p,categorie c,sous_categorie sc WHERE p.pr_id_categorie=c.ca_id AND p.pr_id_sous_categorie=sc.sc_id AND p.pr_id IN ({$usersIDS}) ORDER BY p.pr_id";
$resultat = mysql_query($requete);
$num_rows = mysql_num_rows($resultat);
mysql_query("SET NAMES 'utf8'");
?>
<!DOCTYPE html>
<html>
<head lang="fr">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link type="text/css" media="print" href="css/print.css">
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
<style type="text/css" >
/* PAGE SETTINGS */
.pageRotate
{
-webkit-transform: rotate(-90deg);
-moz-transform:rotate(-90deg);
filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
.rowMainPage {
}
.column {
width: 63mm;
border: solid #000000 1px;
float: left;
position:relative;
padding: 0;
}
/*PAGE ITEMS*/
.logoPuricard{
width: 7em;
top: 0;
margin-left: 38%;
margin-bottom: 5px;
}
/*PRODUCT IMAGE*/
.productImg {
width: 8em;
float: left
}
/*PRODUCT NAME*/
.nom {
font-size: 20px;
font-weight: bold;
margin-left: 2em;
}
/*Product weight*/
.weight {
margin-left: 4em !important;
}
/*Product description*/
.ProductDescription {
}
/*Product container of small peaces(Ingrédients,Valeurs énergétiques etc..) with black border*/
.divSmallContainer {
border: solid 1px #000000;
width: 100%;
/*margin-left: -1em;*/
}
/*Container for valor energetic*/
.valeurEnergContainer {
padding-left: 10px;
}
</style>
</head>
<body class="pageRotate" onload="window.print()">
<!--CONTAINER START-->
<div class="container">
<?php
if($num_rows > 0) {
/*
Start with variables to help with row creation;
*/
$startRow = true;
$postCounter = 0;
$idCheck = 0;
while($num_rows > 0){
$ligne = mysql_fetch_assoc($resultat);
if ($startRow) {
/*LOGO START*/
echo "<img class='logoPuricard' src='./images/logo.jpg'>";
/*LOGO END*/
/*PAGE ROW START*/
echo '<div class="row rowMainPage">';
// /*FIRST COLUMN START*/
// echo '<div class="col-md-12">';
echo "<!-- TEST 6 kolumn -->";
$startRow = false;
}
$postCounter += 1;
?>
<?php
$id = $ligne["id"];
$nom = $ligne["nom"];
$poids = $ligne["poids"];
$ingredients = $ligne['ingredients'];
$description = $ligne['description'];
$valeurs_energetiques = $ligne['valeurs_energetiques'];
$valeurs_nutritionnelles = $ligne['valeurs_nutritionnelles'];
?>
<!-- FIRST COLUMN START -->
<div class="col-md-4 column" >
<!-- Product IMG START -->
<?php if (file_exists('../Assets/produit_'.$id . ".png")) {?>
<img class="productImg" src="../Assets/produit_<?php echo $id; ?>.png" />
<?php } ?>
<!-- Product IMG END -->
<!-- Product NOM START -->
<?php if(isset($nom) && !empty($nom)){
echo "<p class='nom'>". utf8_decode($nom) ."</p><br>";
}?>
<!-- Product NOM END -->
<!-- Product WEIGHT START -->
<?php if(isset($poids) && !empty($poids)){
echo "<p class='weight'> Environ". utf8_decode($poids) . "g" ."</p><br>";
}?>
<!-- Product WEIGHT END -->
<!-- Product DESCRIPTION START -->
<?php if(isset($description) && !empty($description)){
echo "<p class='ProductDescription'>". utf8_decode($description) ."</p><br>";
}?>
<!-- Product DESCRIPTION END -->
<!-- Product INGREDIENT START -->
<?php if( $ingredients){
echo"<div class='divSmallContainer'>";
echo"<b style='text-decoration: underline;'> Ingrédients :</b><br><br>";
echo "<div class='valeurEnergContainer'> $valeurs_energetiques; </div>";
echo"</div>";
}
?>
<!-- Product INGREDIENT END -->
<?php
if($postCounter != 3 || $postCounter != 0) {
echo '</div>'; /*END OF COLUMN*/
}
if ( 3 === $postCounter ) {
echo ' </div>'; /*END OF COLUMN*/
echo '</div><!-- PAGE ROW END-->';
$startRow = true;
$postCounter = 0;
// echo "<span class='breakPage'></span>"; //add page break
}
--$num_rows;
}/*endWhile*/
if ($postCounter !== 0 ) {
echo '</div>';
}
}else {
echo '<div class="page-header"><h1>Pas des resultat</h1></div>';
echo ' <p>desole vous n\'avez pas choisir des produits</p>';
}
if ( 3 === $postCounter || $num_rows == 0 ) {
echo '</div><!-- END OF INTERNAL ROW -->';
$startRow = true;
$postCounter = 0;
}
?>
<!--CONTAINER END-->
</div>
</body>
</html>
There's no need to rotate the page, as this will do just that - rotate EVERYTHING. Just put all the CSS you want for your landscape print layout under the #media print{#page {size: landscape}} media query.

Categories