ajax autocomplete textbox search arrow key selection is not working - javascript

I have a simple auto complete search box in codeignator that displays locations in mysql database results using php "LIKE" function.Everything works fine. i would just like to make it so that when the user starts typing he/she can use the arrow keys to scroll down and press enter on an item just like google. my code is below
<div class="banner_search_inner_box_search" style="margin-top: 15px;">
<input type="text" name="search" class="search" id="searchid" value="" placeholder="Enter a City,Locality" autocomplete="off">
<div id="result"></div>
</div>
My css code
#result
{
position:absolute;
width: 457px;
/*padding:10px;*/
display:none;
margin-top:-1px;
border-top:0px;
overflow:hidden;
border:1px #CCC solid;
background-color: white;
}
.show
{
padding:10px;
border-bottom:1px #999 dashed;
font-size:13px;
height:6px;
}
.show:hover
{
background:#4c66a4;
color:#FFF;
cursor:pointer;
}
JS code
<script type="text/javascript" src="<?=PUBLICPATH?>js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
var AJAXPATH = 'http://localhost/PCenter/';
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url:AJAXPATH + 'search/show_city',
data: dataString,
selectFirst: true,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
somebody please help me

Use the following plugin:
http://jqueryui.com/autocomplete/#remote
It allows you to fetch the results from a remote Data source via AJAX. You may have to change the format of the AJAX response (JSON response), to match the format which autocomplete requires.

Related

How to take multiple images value and push array

I want to do a multiple file upload and I have to convert an image into base64 encoded string. I have one form and two form fields, like firstname & image upload. Suppose a user enters his name and he will upload two photos and he will click submit means, I want convert these two images into base64 string and I want to make my expected JSON format, I don't where I have to change from this code, please anyone update my code
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function() {
$(this).before($("<span/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}), $(" ")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<span id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></span>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
});
)
});
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
// Form Submit
$('#upload').click(function(e) {
e.preventDefault();
var firstName = $("#firstName").val();
var json ={
"rentProperty":
{
"fname" : firstName,
},
"gallery":"not loaded yet"
}
var floor_image;
var filesSelected = document.getElementById("file").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
floor_image = fileLoadedEvent.target.result;
json.gallery=({"image": floor_image });
}
fileReader.readAsDataURL(fileToLoad);
}
console.log(json);
});
});
#import "http://fonts.googleapis.com/css?family=Droid+Sans";
form{
background-color:#fff
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family:'Droid Sans',sans-serif
}
#formdiv{
width:500px;
float:left;
text-align:center
}
form{
padding:40px 20px;
box-shadow:0 0 10px;
border-radius:2px
}
h2{
margin-left:30px
}
.upload{
background-color:red;
border:1px solid red;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0 green;
box-shadow:2px 2px 15px rgba(0,0,0,.75)
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow:0 0 5px rgba(0,0,0,.75)
}
#file{
color:green;
padding:5px;
border:1px dashed #123456;
background-color:#f9ffe5
}
#upload{
margin-left:45px
}
#noerror{
color:green;
text-align:left
}
#error{
color:red;
text-align:left
}
#img{
width:17px;
border:none;
height:17px;
margin-left:-20px;
margin-bottom:91px
}
.abcd{
text-align:center
}
.abcd img{
height:100px;
width:100px;
padding:5px;
border:1px solid #e8debd
}
b{
color:red
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="maindiv">
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Name: <input type="text" name ="firstName" id="firstName"><br><br><br>
<div id="filediv"><input name="file[]" type="file" id="file" multiple/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Submit" name="submit" id="upload" class="upload"/>
</form>
</div>
</div>
</body>
My Expected answer should come like this
{
"rentProperty":
{
"fname" : firstName,
},
"gallery": [
{
"image": "data:image/png/base64.ibokjnerkjdjflkdasafsdnmj........"
},
{
"image": "data:image/jpg/base64.ibokjnerkjdjflkdasafsdnmj........"
}
],
}
I tried like this
$('#upload').click(function(e) {
e.preventDefault();
var firstName = $("#firstName").val();
var floor_image;
var filesSelected = document.getElementById("file").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
floor_image = fileLoadedEvent.target.result;
json.gallery=({"image": floor_image });
}
fileReader.readAsDataURL(fileToLoad);
}
var json ={
"rentProperty":
{
"fname" : firstName,
},
"gallery":"not loaded yet"
}
console.log(json);
});
I am getting answer like this
{
"rentProperty":
{
"fname" : firstName,
},
"gallery":
{
"image": "data:image/png/base64.ibokjnerkjdjflkdasafsdnmj........"
}
}
I think i have to foreach loop and i have to push in to one array, but i am not sure if anyone know means update my answer
You need an array. Just change this string:
json.gallery=({"image": floor_image });
to
json.gallery[]=({"image": floor_image });

jQuery search bar only working one time per page

I am working on a page for pre-registration to events on my website. On this page, people need the ability to add names into as many slots as the event creator would like (so it needs to handle 3 person basketball teams and 50 person banquets). I have had a high quality facebook-like search bar made so that I can neatly search through the database and select the desired people. Sadly I have this search bar being created by a for loop that creates many different ID filled search bars but every one of them is left empty and the first search bar is the only one that is filled.
I found that it deals with the jQuery code at the top of my page. My question/issue is that I need this jQuery to work on multiple search bars on a single page. If anyone can help me accomplish this I'd be greatly appreciative.
The "top code" or JQuery code that pulls from the db successfully is:
$(function(){
$(".search").keyup(function()
{
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
$.ajax({
type: "POST",
url: "../searchMyChap.php",
data: dataString,
cache: false,
success: function(html)
{
$("#divResult").html(html).show();
}
});
}return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
</script>
<style type="text/css">
body{
font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.contentArea{
width:600px;
margin:0 auto;
}
/*
#inputSearch
{
width:350px;
border:solid 1px #000;
padding:3px;
}
*/
#divResult
{
position:absolute;
width:545px;
display:none;
margin-top:-1px;
border:solid 1px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-width: 3px 1px 1px;
border-style: solid;
border-color: #333 #DEDEDE #DEDEDE;
background-color: white;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede;
font-size:12px; height:50px;
}
.display_box:hover
{
background:#0088cc;
//background:#3bb998;
color:#FFFFFF;
cursor:pointer;
}
The for-loop code that prints the search bars is as follows:
for($i = 0; $i < $looper; $i++)
{
echo'
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Member Name:</label>
<input type="text" class="form-control search" name="member'.$i.'" autocomplete="off" id="inputSearch" placeholder="Search...">
<div id="divResult" style="z-index:999; margin-top: 35px;" ></div>
</div>
</div>
</div>';
}
EDIT: Working JSFiddle
The first issue is that with each iteration of the for loop an element is created with id="divResult". An ID should be used once in the whole document. I have changed the for loop to produce an element with class="divResult" instead. If you use this change, remember that your CSS will need to be changed accordingly.
for ($i = 0; $i < $looper; $i++) {
echo '
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Member Name:</label>
<input type="text" class="form-control search" name="member'.$i.'" autocomplete="off" id="inputSearch" placeholder="Search...">
<div class="divResult" style="z-index:999; margin-top: 35px;"></div>
</div>
</div>
</div>';
}
Next we iterate over each .search element. Within each iteration we can find the corresponding 'result' element by using jQuery's next() function, which retrieves the immediately following sibling of an element. If the code is ever changed such that the 'results' element does not appear straight after the `.search' element, this will need changing.
$(function () {
$('.search').each(function(index) {
var $searchElement = $(this);
var $resultElement = $searchElement.next();
console.log(index, $searchElement, $resultElement);
$searchElement.on('keyup', function() {
var inputSearch = $searchElement.val();
var dataString = 'searchword=' + inputSearch;
if (inputSearch != '') {
$.ajax({
type: "POST",
url: "../searchMyChap.php",
data: dataString,
cache: false,
success: function (html) {
$resultElement.html(html).show();
}
});
}
return false;
});
$resultElement.on("click", function (e) {
var $clicked = $(this);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$searchElement.val(decoded);
});
$(document).on("click", function (e) {
var $clicked = $(e.target);
if (!$clicked.hasClass("search")) {
$resultElement.fadeOut();
}
});
$searchElement.on('click', function () {
console.log(index + ' clicked');
$resultElement.fadeIn();
});
});
});

How to show the original elements after the replace with?

I have a div with the name "frined-replace" and an autosuggestion field. When the page loads the contents inside the frined-replace div shown. when we write something to the input field to search then the frined-replace is replaced with the data of the autosuggestion. Now the question is that when i write something the frined-replace div is replaced by the data and when i erase the input field characters which i have entered then i can't reshow the frined-replace div elements.
frined-replace:
<li style="float:left; width:240; margin:2px 0 4px 2px; border-bottom:1px solid #CCC; background-color:#f90; height:30px;">
<a href="<?php echo $config->baseUrlTs;?>messages?user_id=<?php echo $myusrid;?>" >
<img src="<?php echo $config->baseUrl;?><?php echo $imgs;?>" alt="" width="26" height="26" />
<font style="font-weight:bold; color:white"><?php //global $config;
echo $myusrname;
?></font></a>
</li>
and this is the autosuggestion part:
$("#search").keyup(function(e){
var qr = $("#search").val();
if(qr=="")
{
$("#erase").empty();
return;
}
$.ajax({
url: "<?php echo $config->baseUrl;?>/themes/gr-mist/ajax/inbox-ajax.php?str="+$(this).val()+"&user_id="+<?php echo $userid;?>,
context: document.body,
success: function(data){
$("#frined-replace").replaceWith(data);
//$("#search").val('');
//$('#search').val('').empty();
}
});
});
I just made a snippet code which show a possible answer
$("#search").keyup(function(e){
var qr = $("#search").val();
if(qr=="") {
$("#frined-replace").html($("#frined-replace-bck").html());
$("#frined-replace-bck").remove();
$("#erase").empty();
return;
}
if (!$('#frined-replace-bck').length) {
var backup = $("#frined-replace").clone();
backup.prop('id', 'frined-replace-bck');
backup.css('display', 'none')
$("#frined-replace").before(backup);
}
//Replace with your ajax call
$("#frined-replace").html('<li>' + qr + '</li>');
//$("#search").val('');
//$('#search').val('').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<input id="search" type="text"/>
<div id="frined-replace">My initial content</div>
</div>
I fixed it. I made another div with display to none after i show the data in that div instead of replacing it with frined-replace div.
<style type="text/css">
#loadsearch
{
display:none;
width: 250px;
position: absolute;
margin-top: -8px;
height: 100px;
z-index: 1;
margin-left: 2px;
height:auto;
}
</style>
<div id="loadsearch">
</div>
In the jquery
$("#search").keyup(function(e){
var qr = $("#search").val();
if(qr=="")
{
$("#erase").empty();
$("#loadsearch").hide();
return;
}
$("#loadsearch").empty();
$.ajax({
url: "<?php echo $config->baseUrl;?>/themes/gr-mist/ajax/inbox-ajax.php?str="+qr+"&user_id="+<?php echo $userid;?>,
context: document.body,
success: function(data){
$("#loadsearch").show();
$("#loadsearch").append(data);
//Here i am showing the data inthe div instead of replacing
},
});
});

JS remove class from div, when text field in empty?

I have a search bar where the results are displayed centered of the page with a fixed div. And an absolute div covers the page behind the results with a semi transparent black. How could I remove the class ".coverOn" added on the keyup function, If I just deleted what I put into the search field without refreshing the page?
Thanks.
<styles>
.coverOn {
position:absolute;
width:100%;
height:100%;
background-color:rgba(0,0,0,0.7);
z-index:8;
}
#output { /* holds search results */
position:fixed;
left:0;
right:0;
top:130px;
width:400px;
margin:0 auto;
-webkit-border-radius:15px;
-moz-border-radius:15px;
border-radius:15px;
z-index:12;
}
</styles>
<body>
<div id="cover"></div>
<div id="Search">
<input type="text" name="search" onkeyup="searchq();" value="" required class="SearchField" />
<div id="output"></div>
</div>
</body>
<script>
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("../php/productSearch.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
document.getElementById("cover").className = "coverOn";
});
}
</script>
Remove class if searchTxt string is empty:
function searchq() {
var searchTxt = $("input[name='search']").val().trim();
$.post("../php/productSearch.php", {searchVal: searchTxt}, function (output) {
$("#output").html(output);
document.getElementById("cover").className = searchTxt ? "coverOn" : "";
});
}
or since you are using jQuery it can be simpler:
$("#cover").toggleClass("coverOn", searchTxt);
use removeClass('selector');
$('input').on('keyup', function() {
$('.red').removeClass('red');
})
.red {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<div class="red">red</div>
What you could do, rather than operating with classes, is instead of
.coverOn {
position:absolute;
width:100%;
height:100%;
background-color:rgba(0,0,0,0.7);
z-index:8;
}
do
#output:not(:empty) {
position:absolute;
width:100%;
height:100%;
background-color:rgba(0,0,0,0.7);
z-index:8;
}
So long as when you do an empty search, it returns an empty result.
Your resulting javascript would be
function searchq() {
var searchTxt = $("input[name='search']").val();
$.post("../php/productSearch.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});

Javascript autocomplete function href

I´ve the following javascript-function:
<script type="text/javascript">
$(function() {
var data = (<?php include("php/search_new.php"); ?>).Data.Recipes;
var source = [];
for (var i in data) {
source.push({"href": "/php/get_recipe_byID.php?id=" + data[i].ID, "label": data[i].TITLE});
}
$("#searchrecipes").autocomplete({
minLength: 3,
source: source,
select: function(event, ui) {
window.location.href = ui.item.href;
}
});
});
</script>
<input id="searchrecipes" type="text" name="searchrecipes" style="margin-left: 850px; margin-top: 0px; width:170px; background: #fff url(images/search_icon.png) no-repeat 100%;" onblur="this.style.background='#ffffff'; background: #fff url(images/search_icon.png) no-repeat 100%;" onfocus="this.style.background='#c40606'; background: url(images/search_icon.png) no-repeat 100%;" placeholder="Suchen..."></input>
<input type="submit" name="buttonsenden" style="display:none;" value="" width: 5px></input>
The function has already worked but suddenly it stopped working. The problem is, that the href on the dropdown-autocomplete isn´t clickable.
var data = ({"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200}).Data.Recipes;
All the necessary jquery scripts are available.
What can be the problem?
Why not use directly the remote-source, instead of doing this array works?
That's not the way to use PHP and JS together:
var data = (<?php include("php/search_new.php"); ?>)
You can use directly a remote source. It will be loaded by an AJAX request:
$(function() {
$("#searchrecipes").autocomplete({
minLength: 3,
source: "/php/recipe_index.php",
select: function(event, ui) {
window.location.href = ui.item.href;
}
});
See Documentation "source:" parameter or a demo-implementation (view sourcecode)
Cheers. Frank

Categories