Change input autocomplete value - javascript

I have another question: Is there any way to change input autocomplete value dynamically with javascript?
Example:
<input id="myInput"
placeholder="Write something here..."
onchange="changeAutocompleteValue(event)">
<script>
function changeAutocompleteValue(event)
{
var list = ["first", "second", "third"];
event.list = list;
}
</script>
Google example:
Am I able to do it with plain JS? Any suggestion will be great :).

I found
javascript : Auto complete javascript text field
if use existing library then
typeahead.js
typeahead.js / example
function loadXMLDoc(_target, _type,_func) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
data = JSON.parse(xmlhttp.responseText);
_func(data);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open(_type, _target, true);
xmlhttp.send();
}
function ontxtChange(){
var dcc = document.getElementById('autocc');
var dc = document.getElementById('autoc');
dcc.innerHTML = ' ';
var i = 0;
var target = "https://api.github.com/users/mralexgray/repos"
//
if(dc.value.length > 0){
loadXMLDoc(target,'GET',function(data){
data.forEach(function(x){
if(i < 10){
if(x.name.toLowerCase().indexOf(dc.value.trim()) != -1){
dcc.innerHTML += '<p class="accItem">' + x.name.toLowerCase() + '</p>';
i++;
}
}
});
});
}
}
.accItem{
background-color:#333;
color:#fff;
width:200px;
}
#autocc{
width:200px;
}
<body>
<input type="text" id="autoc" onkeypress="ontxtChange()" > example : "am"
<div id="autocc">
</div>
</body>
suggestion--
condition in call ajax (slow with big data)
condition in send/receive data with ajax
hope help you this way...

It is possible, but you will need to write much more code. Your best option to use existing library that handles this for you:
Documentation: https://github.com/devbridge/jQuery-Autocomplete
Demo: http://devbridge.github.io/jQuery-Autocomplete/

Related

How to code navigation key on instant search results?

This is my code:
Html :
<input onkeyup="showResult(this.value)" id="tsearch" class="search-query form-control" type="text" placeholder="Search here ..." name="tsearch"></input>
<div id="livesearch" style="border: 0px none;">
Script :
<script>
function showResult(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border = "0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
}
}
xmlhttp.open("GET", "livesearch.php?q=" + str, true);
xmlhttp.send();
}
</script>
livesearch.php is returning the results once input is provided in the search box. What changes I have to make in the above code so that it provides navigation key support on the search results and remove the results once mouse is pressed in any other area of the page?
Thanks in advance.
You could put all particular search results inside their own DIV container as children of you #livesearch DIV.
Inside you keyup function use the function's event paramenter to fetch the keyCodes for arrow up and down:
left = 37
up = 38
right = 39
down = 40
Then use another function to focus the desired search result.
Hope this helps.

javascript dynamic content not affected when ajax call

I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem
document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}
See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";

Ajax div can't access address bar variable

Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge
Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;
But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.

Need help to improve this largest common substring implementation

I have scanned the web for largest substring implementations to use in my xmlhttp request, however I found that only 1 has worked, in other cases the responsetext hasn't been treated as a string no matter what I have written:
txt = txt + ""; // or
txt = new string(txt);)
This function works, but it is terrible slow. I am just wondering if you code gurus out there could help me improve this algorithm.
The site that I'm calling a xmlhttprequest is looking like this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /</title>
</head>
<body>
<h1>Index of /</h1>
<ul><li> Parent Directory</li>
<li> random/</li>
<li> random_1/</li>
<li> random/</li>
<li> random_1/</li>
<li> random/</li>
<li> random_1/</li>
</ul>
</body></html>
In other words you can strip of all the html tags for better speed, I will just search for the plain text in the html text document.
You can watch the script in action here at tdsoft.se
<html>
<head>
<script type="text/javascript">
var txt;
var buildName = "";
var xmlhttp;
function lcs(a, b) {
var aSub = a.substr(0, a.length-1);
var bSub = b.substr(0, b.length-1);
if (a.length == 0 || b.length == 0) {
return "";
} else if (a.charAt(a.length-1) == b.charAt(b.length-1)) {
return lcs(aSub, bSub) + a.charAt(a.length-1);
} else {
var x = lcs(a, bSub);
var y = lcs(aSub, b);
return (x.length > y.length) ? x : y;
}
}
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("http://tdsoft.se/testni.html",handleXML);
}
var checkState = function(xmlhttp, callback) {
try{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback();
}
else {
// Check back again 1 sec later
setTimeout(checkState, 1000);
}
}
catch(err){
setTimeout(checkState, 1000);
}
};
function handleXML()
{
checkState(xmlhttp, function() {
txt=xmlhttp.responseText;
buildName = "random";
txt = txt.replace(/<[^>]*>/g, "");
var myvar = "";
myvar = lcs(txt, "random");
document.write(myvar);
});
}
</script>
</head>
<body onLoad="myFunction()">
</body>
</html>
Seems like you would want to take a different approach at this.
I'm not exactly sure the point of what you are trying to do but it seems like something like this would be what you want:
You request a Document
Parse the links in the document and store them in an object keyed by their ids with values being their text
Change your lookup function to go after the link list
Here's a code example (using jQuery for simplicity):
//untested!
var links = {};
function successFunction(data) {
var aTags = data.find('a');
aTags.each(function() {
var $this = $(this);
links[$this.attr('href')] = $this.text();
});
}
function lookup(id) {
return links[id] || '';
}
$.ajax({
url: 'requestPage.htm',
success: successFunction
});
EDIT:
If you want to do this non-jquery you can just replace the following things:
$.ajax to your XMLHttpRequest method
data.find('a') to getElementsByTagName
.each(function(){...}) to var i = aTags.length; while(i--) { links[aTags[i].href] = aTags[i].innerHTML; }

How to search a large String

Hi I have the following code
<html>
<head>
<script type="text/javascript">
var xmlhttp;
var allSearchResults = [];
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction(paramm)
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
if (txt.match(paramm)!= -1){
//store all instances in allSearchResults array Here
}
else{
document.getElementById("myDiv").innerHTML = paramm;
}
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction('CXS101289')">Change Content</button>
</body>
</html>
ajax_info.txt
CXS101289_5_R1A06_100628150914
CXS101289_5_R1A06_100628343414
CXS10rfe_5_R1A06_100628150955
CXS101349_5_R1A06_100628150432
CXS154f89_5_R1A06_100628150914
CXS101289_5_R1A06_10062456914
CXS101369_5_R1A06_100628150914
CXS15679_5_R1A06_100628150914
So I want to search this file for the "CXS101289". So after I have run this method, the "allsearchResults" array shall contain ["CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_100628343414","CXS101289_5_R1A06_10062456914"]
Any smart idea on how to implement this?
This should do what you're looking for
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"));
for example after
param = "x";
txt = "x_1 y_2 z_3 x_4 yx_5 z_6 x_7";
result = txt.match(new RegExp("\\b" + param + "\\S*", "g"))
result is ["x_1", "x_4", "x_7"]
Note that if param is going to contain charaters that have a special meaning for a regular expression (for example * or + or ]) then you have to escape them by prepending a backslash.
The initial \b is needed to be sure that your search key is only accepted at the beginning of an item.
function findMatched(text, keyword) {
var arr = text.split('\n');
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
if(arr[i].match(keyword)) {
result.push(arr[i]);
}
}
return result;
}
//...and in your code
if (txt.match(paramm)!= -1){
allSearchResults = findMatched(txt, paramm);
}
It is the only way I can see it solve. But maybe you already taught of this and where asking something else.

Categories