Convert to Text Box search instead of drop down - javascript

I've been using this script to bring back information from a drop down select option, i want to use this same method but in a text box, where the user can input a search instead, is this possible to do? It would be a search engine of sorts. I think i can figure out how to create the search engine part, I just need to covert this first to make sure i can return back a proper result.
My objective is to Allow the user to type in a text field a specific logo he/she wants, and the return is the results of that search. They are searching png images in an array and will select one to complete the form.
function showSub(str) {
var xmlhttp;
if (str=="") {
document.getElementById("txtSub").innerHTML="";
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("txtSub").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSub.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
Html
<tr>
<td width='15%'><div align='right'><strong>Sub-Category</strong></div></td>
<td width='70%'><div id="txtSub"></div></td>
</tr>
Side note: I've seen search queries that give you results on the fly and results that give you results after pressing enter. My current script that uses this is in ajax I believe and gives you the results after the drop down is selected, would it possible to do the same with a text search box?
Edit: Also, if this script is the wrong method to do this, and someone has an alternate suggestion or a script that already does this, i'm very open to other ideas. thanks.

If you want to use a text field input you could do something like:
html
<input type="text" id="searchText" value="" />
javascript/jquery
$(document).on('change', '#searchText', function() {
// Get the search text
var searchText = $(this).val();
// Make sure it isn't empty
if (searchText.length > 0) {
// Send the update request
showSub(searchText);
}
});

Related

Refresh browser / link and still "hit" javascript-function

I have created a list through normal html which have this link to a "details" page. URL: index.php?page=userDetails&usersId=10. This may be changed if I get the correct solution for my challenge :)
At the "details page" I have made a dropdown which basicly insert (GET) a id to PHP and PHP generates content.
The dropdown looks like this
<select name="users" onchange="showUser(this.value)" class="selectpicker">
<option data-tokens="10" value="10">user-10</option>
<option data-tokens="41" value="41">user-41</option>
<option data-tokens="9" value="9">user-9</option>
<option data-tokens="8" value="8">User-8</option>
</select>
<!-- This is where PHP-content will be printed..... -->
<div id=\"txtHint\"><b>Person info will be listed here...</b></div>
Javascript looks like this (function showUser)
function showUser(
{
if(str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
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("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","logic/do.php?action=ajaxReceive&input="+str,true);
xmlhttp.send();
}
}
The Id (from database) is received as $_GET[input] and everything actually works fine, and I can print ID at the moment.
My problem is 2 things:
1) When I refresh browser the ID is not stored. I suppose this can be done by cookie or session, but how do I keep the ID and "insert" it into the function so I stay on user 8, 10, 14 or what ever user I was looking at?
2) The same problem is the actual link where I link from one page to a whole other page. This is neccesary since I am no super-expert so I am reluctant to run everything as pure javascript/jQuery. I fix things best at PHP-side so sometimes I need a little breath :)
I hope you understand my probably rather basic problem...
I am looking forward to some input concerning my little challenge :)
Cheers Nikolaj
You could use window.onbeforeunload to execute a script/function before a page is unloaded. You could send the userID to your PHP script and let that store the userID.
HTML
<element onbeforeunload="yourFunction()">
Reference: http://www.w3schools.com/tags/ev_onbeforeunload.asp
Javascript
window.onbeforeunload = function() { /* Your function send to e.g. PHP here */ }
jQuery
$(window).on('beforeunload', function(){ /* Your function send to e.g. PHP here */ });

Getting "Cannot read property 'innerHTML' of null" but I have that id initiated

I have read on here that usually this problem comes up when the specific div isn't loaded yet or just isn't there. I have this code looping so even if it wasn't fully loaded the first time it will be by the next iteration. Also I for sure have a div with the id participants.
<div id="participants">
<div class="sectionhead wow bounceInUp" data-wow-duration="2s">
<span class="bigicon icon-user"></span>
<h3>Participants<h3>
<h4>Check out who has signed up already!</h4>
<hr class="separetor">
<div id"test" onload="updateVariables()">
</div>
</div>
</div>
<script>
setInterval(function(){
updateVariables();
},4000);
updateVariables = function() {
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)
{
var info = xmlhttp.responseText;
console.log(info);
var out = info.split("\n");
console.log(out[1]);
var outLen = out.length;
for(x = 0; x < outLen; x++){
document.getElementById("test").innerHTML += out[x];
document.getElementById("test").innerHTML += "<br>";
}
}
}
xmlhttp.open("GET","../php/tour.txt",true);
xmlhttp.send();
}
</script>
That's pretty simple. In your real page you have a simple typo mistake. Instead of
<div id"test" onload="updateVariables()">
You should have
<div id="test" onload="updateVariables()">
EDIT: the easiest way to locate such errors on your own is debugging. I consider at the moment that Chrome dev tools is the best option, however you can use dev tools F12 of any browser, since this problem is simple. I will demonstrate an example on Chrome.
In console you will see errors happening. To the right of the error you can see a link to the place in sources where it happens.
A click on (index):247 takes you there in debugger window. Where you can place a breakpoint. Once you hit the breakpoint you have very powerful tools provided by Chrome. You can add variables to watch list, you can execute any code in console, you can trace the DOM (Elements tab) at current moment.
The typo of interest can be easily located by copying the code you suppose is working to console document.getElementById("test").
Now you start getting puzzled what the heck it returns null instead of a div. You go to elements tab and search for test by Ctrl+F. You find the text in html however after roaming around with beer you notice that the id is actually not defined due to wrong syntax

Drop down menu with hover and up and down key selections - conflict code

I have created a drop down menu with the help from stackoverflow users and this
LINK HERE from w3schools.
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
However, I am having problems implementing this code to include a function that will pick up on the user selecting without the use of a mouse (i.e key up and key down). I have tried to implement the following example from another thread on stackoverflow: LINK HERE and a FIDDLE HERE but to no avail.
var active = document.querySelector(".hover") || document.querySelector(".dropdownItemContainer li");
document.addEventListener("keydown",handler);
document.addEventListener("mouseover",handler);
function handler(e){
console.log(e.which);
active.classList.remove("hover");
if (e.which == 40){
active = active.nextElementSibling || active;
}else if (e.which == 38){
active = active.previousElementSibling || active;
}else{
active = e.target;
}
active.classList.add("hover");
}
What happens is depending on where I place my code in my javascript sheet, it either does not work at all, or when a down key is pressed, it automatically jumps back up to the top selection. If I hold down the down key, it rapidly filters through all selections until it hits the bottom, then flicks back again to the top selection.
By implementing an alert in between each up key and down key, the result works. Therefore something is conflicting.
Does anyone have any clues on how to remove this conflict? Or are able to overcome this?
I am not interested in jquery, and any help or further links that may be of help will be welcomed.

Refresh only one div with AJAX

I want to dynamically reload only one div in my page every five seconds. But in my response I get the content of the whole page... How can I get only the content of the specified div ?
<script>
function ajaxrefresh()
{
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)
{
//Here i want only the content for the div from the response
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else
{
//alert("state: "+xmlhttp.readyState)
//alert("status: "+xmlhttp.status)
}
}
xmlhttp.open("GET","http://${localHostAddress}:8080/adress",true);
xmlhttp.send();
var t=setTimeout(ajaxrefresh,5000);
}
window.load = ajaxrefresh();
</script>
Someone has already ask something like this on SO. Best voted-up is to create an invisible div in your page, and fill it with the AJAX response to be able to get back element you need with hiddenDiv.getElementById("myDiv").
As you can not use Jquery, I think your best bet is in response to ajax call return only the div contents from server side. this way your response size will be smaller and hence faster too...
if you can not change the response of request use below code
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//Here i want only the content for the div from the response
var mydiv= document.getElementById("myDiv");
var doc=document.createElement("div");
doc.innerHTML=xmlhttp.responseText;
document.body.appendChild(doc); // Note append temp to document
mydiv.innerHTML=doc.getElementById("theDivYouWant")
.innerHTML;
document.body.removeChild(doc);// Note remove temp from document
May be you will get some idea from below script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_div_refresh = setInterval(function(){
$('#load_data').load('fb_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
You could try something like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//Here i want only the content for the div from the response
var doc=document.createElement("div");
doc.innerHTML=xmlhttp.responseText;
document.getElementById("myDiv").innerHTML=doc.getElementsByTagName("div")[5]
.innerHTML
Here 5 is just a random number, if the div is always fixed you can use the number that the div is located and if it's not you need to loop through the divs and find the one you're looking for (maybe based on id).

How to get unnamed elements from an external webpage using AJAX?

At the moment I'm trying to get an element off an external website using AJAX, so far I've (hopefully) managed to get the page:
var xmlhttp;
var version;
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)
{
version=xmlhttp.innerHTML;
}
}
xmlhttp.open("GET","http://www.minecraftwiki.net/wiki/Minecraft_Wiki",true);
xmlhttp.send();
Now I just need to find a way to get the contents:
<dd> Current PC version:
<b>
<a href="/wiki/Version_history#1.2.5" title="Version history">
1.2.5
</a>
</b>
</dd>
I've checked the source code of the url and sadly the element I want is unnamed (Has no id=" "), so is it still possible to do so? And if so, how? Thanks
First, you're making a cross-domain request, so unless you're using a browser that allows cross-domain AJAX, this is most likely not going to work for you without using a server-side proxy.
However, to answer your original question, you don't need an id attribute to access an element. While helpful, you can access an element in any number of ways.
Class Selectors
var col = document.getElementsByClassName("the-class");
Then loop through the collection until you find the element you want.
jQuery Selectors:
jQuery Selectors are perhaps the easiest way to handle DOM manipulations and get access to the element you are interested in:
// example of an attribute selector:
var exampleHTML = $('div[title="example"]).html();
There is also XPath, but from my experience jQuery CSS Selectors are more modern, robust, and help speed up the development process.

Categories

Resources