modify jquery slideshow code to autoplay - javascript

I found some code in an article on daniweb.com for a jquery slideshow and got it working pulling data from mysql. I want to modify it so the slide changes automatically every 5 seconds or so, instead of having to click the buttons but don't know how to modify this code to do that...
Here's the current code: It uses a mysql database and php to pull used car info from a table and then display in a slideshow. The idea is to run this on a rasPi with a 7-10" display at our cashier counter or waiting room for customers to see...
Any help would be greatly appreciated, thank you!
$(document).ready(function(){
var currentPosition = 0;
var slideWidth = 950;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div>')
// Float left to display horizontally, readjust .slides width
.css({
'float' : 'left',
'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert controls in the DOM
$('#slideshow')
.prepend('<span class="control" id="leftControl">Clicking moves left</span>')
.append('<span class="control" id="rightControl">Clicking moves right</span>');
// Hide left arrow control on first load
manageControls(currentPosition);
// Create event listeners for .controls clicks
$('.control')
.bind('click', function(){
// Determine new position
currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
// Hide / show controls
manageControls(currentPosition);
// Move slideInner using margin-left
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
});
});
// manageControls: Hides and Shows controls depending on currentPosition
function manageControls(position){
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
}
});
* {
font-family:Arial;
}
body {
width:800px;
height:572px;
background:linear-gradient(#117dc8,#15527c);
}
.header {
color:white;
font-size:28px;
margin-left:20px;
margin-top:10px;
}
.logo {
position:absolute;
margin-left:720px;
margin-top:-30px;
z-index:10;
width:250px;
}
.container {
position:relative;
background-color:#fafafa;
width:940px;
height:480px;
border-radius:10px;
margin-top:10px;
margin-left:6px;
padding:5px;
z-index:6;
}
#carDisplay {
width:915px;
height:455px;
padding:10px;
border:none;
}
.contact {
position:absolute;
color:white;
margin:15px 80px;
font-size:20px;
}
* {
font-family:Arial;
}
#cert {
color:#e3001b;
}
.cartitle {
font-size:30px;
margin-left:10px;
}
.stock {
font-size:14px;
font-size:18px;
color:#999;
margin-left:10px;
}
.carimg {
width:480px;
padding:5px;
margin-left:10px;
box-shadow:0px 2px 5px 1px #bbb;
}
.details {
padding:30px;
font-size:25px;
}
.price {
font-size:35px;
font-weight:bold;
color:#333;
text-align:center;
margin-top:-20px;
margin-bottom:10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Used Car New Arrivals</title>
<link rel="stylesheet" href="css/mainstyle.css">
<link rel="stylesheet" href="css/framestyle.css">
<script src="jscript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div class="header"><i>Used Car New Arrivals | </i><span style="font-size:20px;">Falmouth Toyota</span></div>
<img class="logo" src="ft-logo.png" />
<div class="container">
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "usedcars";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM usedcars";
$result = mysqli_query($conn, $sql);
$num = mysql_num_rows($result);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div id='slideshow'>
<div id='slidesContainer'>
<div class='slide'>
<table class='tableStyle'>
<tr>
<td colspan='2'><div class='stock'>Stock: " . $row["stock"] ."</div></td>
</tr>
<tr>
<td colspan='2'><div class='cartitle'><b><span id='cert'>" . $row["certified"] . "</span> " . $row["preowned"]. " " . $row["year"] . " " . $row["make"] . " " . $row["model"] . " " . "</b><span style='font-size:18px;color:#999;'> - " . number_format($row["mileage"]) . " miles</span></div></td>
</tr>
<tr>
<td colspan='2'><hr /></td>
</tr>
<tr>
<td><img class='carimg' src='" .$row["img"] . "' /></td>
<td class='details'><div class='price'>Price: $" . number_format($row["price"]) ."</div><br>
<hr style='margin-top:-25px;'/>
<b>Vehicle Features</b>
<ul>
<li>" . $row["feat1"] . "</li>
<li>" . $row["feat2"] . "</li>
<li>" . $row["feat3"] . "</li>
<li>" . $row["feat4"] . "</li>
</ul>
</td>
<tr>
</table>
</div>
</div>
</div>";
}
}
else {
echo "<span>No images available</span>";
}
mysqli_close($conn);
?>
</div>
<div class="contact">VISIT OUR SHOWROOM FOR MORE INFORMATION ON ANY OF THESE VEHICLES</div>
</body>
<script src="jscript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</html>

Try adding the following code inside a script tag. Feel free to change the slide change duration as per your requirement.
Here 5000 means 5*1000 milli seconds, which is 5 seconds.
window.setInterval(function() {
$('#rightControl.control').click();
}, 5000);
Accept this answer if it helps.
Update: Playing the slideshow continuously (looping)
Note: Replace the existing animate function with the below snippet
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
}, function() {
// if last slide then move the pointer to 1st slide
if(currentPosition == numberOfSlides-1) {
currentPosition = -1;
}
});

Related

Jquery horizontal image gallery - retain clicked image to the middle

I have a horizontal image gallery, the images for which is populated from a thumbnail folder. I want to create a utility where the clicked image always remain at the middle of the thumbnail image palette. Similar to the question asked here.
A minimal version of the code is as follows:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#loaded_img_panel {
border-top: solid 0.3em #f1ded9;
display:flex;
flex-wrap: nowrap;
overflow-x:auto;
padding: 10px 0 0 0;
}
#loaded_img_panel > ul > li {
list-style: none;
}
#loaded_img_panel ul li img {
display: inline;
width: 210px;
height:175px;
cursor: pointer;
}
#loaded_img_panel img.active{
border: 0.4em solid red;
padding : 5px;
}
#loaded_img_panel > caption {
display:block;
}
#loaded_img_panel img:hover {
opacity: 0.5;
}
</style>
</head>
<body>
<div class="book-list-headbox">
<div class="page-number-box">
<label for="" id="total-page" value="" class="mb-0"></label>
<span class="separator">of</span>
<input type="text" id="current-page" value="1">
</div>
</div>
<div class="loaded_img_panel" id="loaded_img_panel">
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
window.addEventListener('load', function(e) {
var matchLst = "thumb";
var project = "upload";
if (matchLst !== null && matchLst !=="") {
$.post("loadimages.php", { 'project' : project,'matchLst' : matchLst }, function(output){
$("#loaded_img_panel").html(output).show();
});
}
})
$(function(){
$('#gotoframe').change(function() {
var i = $(this).val() -1;
activeBook(i);
localStorage.setItem('clicki', i);
});
$('#loaded_img_panel').on('click', 'img', function() {
activeBook($(this).index());
});
function activeBook(i){
$('#loaded_img_panel img').removeClass('active');
var active = $('#loaded_img_panel img').eq(i).addClass('active');
var left = active.position().left;
console.log("firstleft: " + left);
var currScroll= $(".loaded_img_panel").scrollLeft();
var contWidth = $('.loaded_img_panel').width()/2;
var activeOuterWidth = active.outerWidth()/2;
left= left + currScroll - contWidth + activeOuterWidth;
$('.loaded_img_panel').animate( {
scrollLeft: left
},'slow');
}
});
</script>
loadimages.php
<?php
session_start();
$project = $_POST['project'];
$match = $_POST['matchLst'];
$_SESSION['matchLst'] = $match;
$tardir = "projects/" . $project . "/" . $match . "/thumb/*.jpg" ;
$imgdir = "projects/" . $project . "/" . $match . "/" ;
$files = glob($tardir);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $imgdir . $imgname;
$filnam = substr($filname, -5);
$filnam = rtrim($filnam);
echo '<ul class="item" id="item">';
echo '<li class="book"><img src="'.$img.'" id="thumbNails'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
?>
The php code renders the images from the folder. When I click on the image from the gallery, instead of providing the position of the image, I get static values till I use the scroll bar to select some of the images that were not visible onload. Those clicks returns the position values in negative. What I am trying to do is given as an example here.

Smooth scrolling using javascript on anchor link

I want to make smooth scrolling using javascript in php program
As shown in image if i clicked on the customer from my left side bar then i want to smooth scrolling using javascript onclick function what i do?here i pass dynamic id whic are i fetched from my database
<div class="col-md-3 col-sm-12" >
<ul data-spy="affix" data-offset-top="205" class="myclasss">
<?php
foreach($var as $name) { ?>
<a id="#<?php echo $name['name'];?>" class="list-group-item" onclick="scrollFaq(this.id);"><?php echo $name['name'];?> </a><?php } ?>
</ul>
</div>
<div class="col-md-9 col-sm-12 ">
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader" id="<?php echo $data['name'];?>"> <?php echo $data['name'];?> </div>
<div class="panel-group" ">
<?php
foreach($data['data'] as $dat){ ?>
<div class="panel panel-default">
<div class="panel-heading ">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#col<?php
echo $v1;?>" ><?php echo $dat['questions'];?> </a>
</h4>
</div>
<div id="col<?php echo $v1;?>" class="panel-collapse collapse ">
<div class="panel-body">
<?php echo $dat['answer'];?>
</div>
</div>
</div>
<script>
function scrollFaq(str){
alert(str);
}
</script>
Try This :
function scrollFaq(str){
$('html,body').animate({scrollTop:$("#"+str).offset().top}, 500);
}
Make sure you give this Id to your div in for loop like this
<div class="col-md-9 col-sm-12 ">
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader" id="<?php echo $data['name']; ?>">
<?php echo $data['name'];?>
</div>
<?php } ?>
</div>
A simple example of how you could achieve the smooth scrolling to an element without using jQuery.
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Smooth scroll to element without jQuery</title>
<script>
function scrollFaq( event ){
event.preventDefault();
/*
Current position and target position
Note: I used `dataset.name` rather than
adding the desired ID as an argument to this
function ~ see html below
*/
var cp=event.target.offsetTop;
var fp=document.getElementById( event.target.dataset.name ).offsetTop;
/*
increase step for larger jump per time period
increase time for longer animation
*/
var step=100;
var time=10;
/* initial step */
var pos = cp + step;
/* self-executing anonymous function */
(function(){
var t;
/* increment the position */
pos+=step;
/* clear the timer if we are at the correct location */
if( pos >= fp ){
clearTimeout( t );
return false;
}
/* do the actual scroll */
window.scrollTo( 0, pos );
/* re-run the function until we reach the correct location */
t=setTimeout( arguments.callee, time );
})();
}
</script>
<style>
.large{
margin:0 0 100rem 0;
border:1px solid black;
display:block;
height:100rem;
font-size:1.5rem;
}
a{
display:block;
clear:none;
margin:0 1rem 1rem 1rem;
width:200px;
padding:1rem;
font-size:1rem;
background:blue;
color:white;
border:1px solid black;
}
</style>
</head>
<body>
<?php
$names=array(/* some random names */
'marilyn','jane','rita','sue','bob','customer','worker'
);
foreach( $names as $name ){/* Note the use of the dataset attribute!!! */
echo "$name";
}
foreach( $names as $name ){
echo "<div id='$name' class='large'>$name</div>";
}
?>
</body>
</html>
Or, a better approach that doesn't involve inline event handlers and now uses your original classNames.
The Javascript function does not need to be declared inside whatever loop you have - indeed to do so would be incorrect. Declare the functions at the top of the page and invoke accordingly as shown here. You could copy either example, save and run to see the scroll effect -then it is trivial to adapt to your "use-case"
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Smooth scroll to element without jQuery</title>
<script>
function scrollFaq( event ){
event.preventDefault();
/*
Current position and target position
Note: I used `dataset.name` rather than
adding the desired ID as an argument to this
function ~ see html below
*/
var cp=event.target.offsetTop;
var fp=document.getElementById( event.target.dataset.name ).offsetTop;
/*
increase step for larger jump per time period
increase time for longer animation
*/
var step=50;
var time=10;
/* initial step */
var pos = cp + step;
var t;
(function(){
/* increment the position */
pos+=step;
/* clear the timer if we are at the correct location */
if( pos >= fp ){
clearTimeout( t );
return false;
}
/* do the actual scroll */
window.scrollTo( 0, pos );
/* re-run the function until we reach the correct location */
t=setTimeout( arguments.callee, time );
})();
}
function bindEvents(event){
/*
Get a nodelist containing all the anchors of class "list-group-item"
*/
var col=document.querySelectorAll('a.list-group-item');
/*
Some browsers do not support using the forEach operator on a nodelist
so convert the nodelist ( which is array like ) into a true array
so that "forEach" can be used.
*/
Array.prototype.slice.call( col ).forEach(function(e,i,a){
/*
here
----
"e" refers to the actual DOM node "a"
"i" refers to the "index" within the array
"a" is the array itself
Assign an "onclick" event listener making sure that
the "passive" flag is set to FALSE in this instance
otherwise you will get an error
"Unable to preventDefault inside passive event listener invocation."
*/
e.addEventListener( 'click', scrollFaq, { passive:false, capture:false });
});
}
/*
Bind the events when the DOM is ready - here we can set the "passive" flag to true
*/
document.addEventListener( 'DOMContentLoaded', bindEvents, { capture:false, passive:true } );
</script>
<style>
.faqHeader{
margin:0 0 100rem 0;
border:1px solid black;
display:block;
height:100rem;
font-size:1.5rem;
}
a.list-group-item{
display:block;
clear:none;
margin:0 1rem 1rem 1rem;
width:200px;
padding:1rem;
font-size:1rem;
background:blue;
color:white;
border:1px solid black;
}
</style>
</head>
<body>
<a name='top'></a>
<?php
$names=array(/* some random names */
'marilyn','jane','rita','sue','bob','customer','worker'
);
foreach( $names as $name ){/* Note the use of the dataset attribute!!! */
echo "<a class='list-group-item' href='#' data-name='$name'>$name</a>";
}
foreach( $names as $name ){
echo "
<div class='faqHeader' id='$name'>
<a href='#top'>$name</a>
</div>";
}
?>
</body>
</html>

How to hide title "City" when click on that div in php page?

I am trying to hide the title, "City", when someone clicks on a div. For ex. if a click on Victoria div, then title, "City", is hidden for that div only, other divs remain unaffected. If you click on Toronto div, its title "City" is hidden and title of Victoria div is shown. It's similar to my previous question, "How to use same onclick function multiple times in php page?", but it won't work here. Any solution with javascript, Jquery?
Php Code :
<?php
$link = mysqli_connect("localhost", "root", "", "test");
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM sample";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo "<div style='border: 2px solid black;'><p class='CityTitle".$row['id']."'>City</p>". $row['UserCity'] ."</p></div></br>";
}
// Close result set
mysqli_free_result($result);
}
else
{
echo "No records matching your query were found.";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Do you want following behavior:
$(document).ready(function() {
$(".cityContainer > div").click(function() {
$(".cityContainer").find(".active").removeClass("active");
$(this).addClass("active");
});
});
.active .CityTitle {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="cityContainer">
<div style='border: 2px solid black;'>
<p class='CityTitle'>City</p>Victoria</div>
</br>
<div style='border: 2px solid black;'>
<p class='CityTitle'>City</p>Toronto</div>
</br>
<div style='border: 2px solid black;'>
<p class='CityTitle'>City</p>Ottawa</div>
</br>
</div>
I think below solution may be helpfull to you , create a click event of the div , and find the class 'CityTitle' which you right in you code and hide using the class. Try this code:
$('document').on('click','div',function(){
$(this).find('.CityTitle').hide();
})
I hope this will help to you.
$('.cityName').click(function(){
$(this).parent().find('.cityHeading').hide();
})
.cityBorder{border:1px solid #000; padding:10px; margin-bottom:10px}
.cityHeading{display:block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cityBorder"><div class="cityHeading">City</div><div class="cityName">Ottawa</div></div>
<div class="cityBorder"><div class="cityHeading">City</div><div class="cityName">victoria</div></div>
<div class="cityBorder"><div class="cityHeading">City</div><div class="cityName">st.john's</div></div>
<div class="cityBorder"><div class="cityHeading">City</div><div class="cityName">Totonto</div></div>
<div class="cityBorder"><div class="cityHeading">City</div><div class="cityName">quebee city</div></div>
Hope this makes you happy

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

need help on ajax suggestion dropdown

I Have an ajax suggestion dropdown and i want to make it display a number of team names but it displays ".$team."
My HTML is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<style type="text/css">
#mainContainer{
width:660px;
margin:0 auto;
text-align:left;
height:100%;
border-left:3px double #000;
border-right:3px double #000;
}
#formContent{
padding:5px;
}
/* Big box with list of options */
#ajax_listOfOptions{
position:absolute; /* Never change this one */
width:175px; /* Width of box */
height:250px; /* Height of box */
overflow:auto; /* Scrolling features */
border:1px solid #317082; /* Dark green border */
background-color:#FFF; /* White background color */
color: black;
text-align:left;
font-size:0.9em;
z-index:100;
}
#ajax_listOfOptions div{ /* General rule for both .optionDiv and .optionDivSelected */
margin:1px;
padding:1px;
cursor:pointer;
font-size:0.9em;
}
#ajax_listOfOptions .optionDiv{ /* Div for each item in list */
}
#ajax_listOfOptions .optionDivSelected{ /* Selected item in the list */
background-color:#317082;
color:#FFF;
}
#ajax_listOfOptions_iframe{
background-color:#F00;
position:absolute;
z-index:5;
}
form{
display:inline;
}
</style>
</head>
<body>
<script type="text/javascript" src="javascript/ajax.js"></script>
<script type="text/javascript" src="javascript/ajax-dynamic-list.js"></script>
<center>
<form>
<fieldset>
<h1>Enter your team team name to see starting 11 and Crest</h1>
<table border="0">
<tr>
<td><label for="team">Team: </label></td>
<td><input type="text" id="team" name="team" value="" onkeyup="ajax_showOptions(this,'getTeamsByLetters',event)">
<input type="hidden" id="team_hidden" name="team_ID"><!-- THE ID OF the country will be inserted into this hidden input --></td>
</tr>
</table>
</fieldset>
</form>
</center>
</body>
</html>
This takes from my php which has the list of teams stored here which the html gets from
<?php
$string =
"arsenal,
manchester united,
manchester city,
cheslea,
tottehnam hotspur,
southampton,
everton,
aston villa,
leicester city,
westham united,
newcastle united,
queens park rangers,
sunderland,
swansea,
hull city,
west bromwich albion,
crystal palace,
burnley,
stoke city";
$aTeams = explode(',', $string);
if(isset($_GET['getTeamsByLetters']) && isset($_GET['letters'])){
$letters = $_GET['letters'];
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
//$res = mysql_query("select ID,teamName from ajax_countries where TeamName like '".$letters."%'") or die(mysql_error());
foreach($aTeams as $key => $team) {
$team = strtolower($team);
if(strpos($team, $letters)!==false)
echo $key."###".$team."|";
}
}
?>
you need to collect the results to some variable then echo it:
if(isset($_GET['getTeamsByLetters']) && isset($_GET['letters'])){
$letters = $_GET['letters'];
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
//$res = mysql_query("select ID,teamName from ajax_countries where TeamName like '".$letters."%'") or die(mysql_error());
$result = "";
foreach($aTeams as $key => $team) {
$team = strtolower($team);
if(strpos($team, $letters)!==false)
$result .= $key."###".$team."|";
}
print_r($result) // see in your console what value it gives in response.
}
echo $result;
Your php function is not returning anything. Plus, you are echoing every single team, but you are not attaching it to the others. Can you provide the ajax_showOptions function? I can't find it
What happens if you try with:
$res = "";
foreach($aTeams as $team) {
$team = strtolower($team);
if(strpos($team, $letters)!==false)
$res.= $key."###".$team."|";
}
return $res;

Categories