...

View Full Version : Resolved Trying to get a javascript array to a html combo box



Deadeye
03-13-2009, 11:23 PM
Good day to all the people of programing land, I need your help once more.

This is what I have:



function stateChanged()
{
if (xmlHttp.readyState==4)
{
var myString = xmlHttp.responseText;
//Is this a array?
var mySplitResult = myString.split(" , ");
document.getElementById("Sugestion").innerHTML=mySplitResult;
//document.getElementById("Sugestion").innerHTML=xmlHttp.responseText;
}
}


xmlHttp.responseText holds the string, an example of such string is:
John Emerson , John Lennon , John Abraham , John Travolta

The Problem: I'm trying to get the string in array form (this code is in a external JavaScript file) to a html file and once there it should go into a combo box (or a drop down box which ever name a person prefers). I just can't get it there for some reason and I kinda need help.

This is the html file by the way.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Auto Load Form</title>
<link rel='stylesheet' type='text/css' href='styles.css' />

<script type='text/javascript' src="suggestion.js">

</script>

</head>
<body>
<form>

<div>
<div><h1>Ajax Auto Load Form</h1></div>
<div><br></div>
<div>Type inn a name: </div>
<div>
<div><input type="text" id="txt1" size='20' onkeyup="Worker(this.value)" /></div>
</div>


<p>Suggestions: <span id="Sugestion"></span></p>



</div>

</form>
</body>
</html>




Thanks in advance.

Henley
03-13-2009, 11:34 PM
Assuming that the select list is created with the responseText, will you then expect the list to "narrow" as the user types?

How many "Workers" are there?

Deadeye
03-13-2009, 11:42 PM
Yes the list narrows down as you type in more or expands as you take out stuff.

For instance writing john would give me John Emerson , John Lennon , John Abraham , John Travolta
While John E would give me just John Emerson.

This is the worker function:


function Worker(str)
{
if (str.length < 3)
{
document.getElementById("Sugestion").innerHTML="Ekki ngu langt";
return;
}
else if(str.length >=3)
{
xmlHttp=createXmlHttpRequestObject();

if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
else
{
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
}
}

Henley
03-13-2009, 11:48 PM
Yes, but are there 5000 "Workers" that might be returned with the responseText?

Is there one set, of a specific length?

I have many variations of this kind of code. But, they all require a finite array.

Your responseText can create that array, your split would work.

But, to keep making an AJAX call for each onkeyup, isn't efficient. The server doens't need to be involved.

JavaScript can use the finite array and continue to narrow the select options, onkeyup.

Make sense?

Deadeye
03-13-2009, 11:58 PM
I'm just going to post the whole code, I know I should have posted it all at once but it kinda slipped my mind.

I programed it so every time you press a button it goes through a list of names and returns appropriately.

Also I don't try to program arrays with finite lengths, meaning I don't but numbers there I let the program calculate that because then I can names at any point.

Here is the whole thing.

Index.hmtl


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Auto Load Form</title>
<link rel='stylesheet' type='text/css' href='styles.css' />

<script type='text/javascript' src="suggestion.js">

</script>

</head>
<body>
<form>

<div>
<div><h1>Ajax Auto Load Form</h1></div>
<div><br></div>
<div>Type inn a name: </div>
<div>
<div><input type="text" id="txt1" size='20' onkeyup="Worker(this.value)" /></div>
</div>


<p>Suggestions: <span id="Sugestion"></span></p>



</div>

</form>
</body>
</html>


Suggestion.js


function Worker(str)
{
if (str.length < 3)
{
document.getElementById("Sugestion").innerHTML="Ekki ngu langt";
return;
}
else if(str.length >=3)
{
xmlHttp=createXmlHttpRequestObject();

if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
else
{
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
}
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
var myString = xmlHttp.responseText;

var mySplitResult = myString.split(" , ");
document.getElementById("Sugestion").innerHTML=mySplitResult;
//document.getElementById("Sugestion").innerHTML=xmlHttp.responseText;
}
}


//g veit a g meira og minna copy+paste aferina sem sndir okkur en hn var bara svo g :)
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp=null;
// this should work for all browsers except IE6 and older
try
{
// try to create XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE6 or older
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
// try every prog id until one works
for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
{
try
{
// try to create XMLHttpRequest object
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e) {}
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}


gethint.php


<?php
//Stillt svona svo a er ekkert cache
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
include_once "class.sql.php";

$ListOfNames;
$sql = new SQL();
$ListOfNames = $sql->AllNames();

//Nr strengin r slini
$q=$_GET["q"];

if (strlen($q) > 0)
{

$SuggestedNames="";

while($row = mysql_fetch_array($ListOfNames))
{

if (strtolower($q)==strtolower(substr($row['Nafn'],0,strlen($q))))
{
if ($SuggestedNames=="")
{
$SuggestedNames = $row['Nafn'];
}
else
{
$SuggestedNames = $SuggestedNames." , ".$row['Nafn'];
}
}
}
}


//Ef SuggestedNames er ekkert hefur a ekki fundi neitt annars birtir a ll nfn sem passa
if ($SuggestedNames == "")
{
$response="no suggestion";
}
else
{
$response = $SuggestedNames;
}


//Skila nfnunum
echo $response;
?>


class.sql.php


<?php
class SQL
{
private $connection;

//Tenging Fer Fram
public function __construct()
{
$this->connection = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("skilaverk2") or die(mysql_error());
}

//Nfnin eru n hr
public function AllNames()
{
$view = mysql_query("select * from nafnalisti") or die(mysql_error());
return $view;
}
}
?>


Hope I made things clearer. :P

Henley
03-14-2009, 12:00 AM
Here's a typical example.

The option value and option text are the same.

I believe that you'll be able to take this example, and complete your project.




<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Smart Select List</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

var smartOptions = [];

var allOptions = [];
allOptions[0] = "Babich, Timothy";
allOptions[1] = "Cahoon, Ron";
allOptions[2] = "Atwood, James";
allOptions[3] = "Cannon, Edith";
allOptions[4] = "Allen, Mike";
allOptions[5] = "Bailey, Mary";
allOptions[6] = "O'Donnell, Patrick";
allOptions[7] = "Alexander, Allison";
allOptions[8] = "Baker, George";
allOptions[9] = "Conner, Anthony";
allOptions[10] = "O'Grady, Lisa";

function buildList(isForm,nArray){

for (i=0; i<nArray.length; i++)
{
nOption = document.createElement('option');
isData = document.createTextNode(nArray[i]);
nOption.setAttribute('value',nArray[i]);
nOption.appendChild(isData);
isForm.isList.appendChild(nOption);
}
}

function buildSmartOptions(isForm){

matchStr = isForm.isText.value.toLowerCase();
if (matchStr != "")
{
smartOptions.length = 0;
n = 0;
endClip = matchStr.length;
for (i=0; i<allOptions.length; i++)
{
if (matchStr == allOptions[i].slice(0,endClip).toLowerCase())
{smartOptions[n++] = allOptions[i]}
}
isForm.isList.length = 1;
for (i=0; i<smartOptions.length; i++)
{
buildList(isForm,smartOptions);
}
if (smartOptions.length > 5){isForm.isList.size=6}
else {isForm.isList.size = smartOptions.length+1}
}
if (matchStr == ""){init()}
}

function getChoice(isChoice){

alert(isChoice);
}

function init(){

isForm = document.forms[0];
isForm.isList.length = 1;
isForm.isList.size = 1;
allOptions.sort();
buildList(isForm,allOptions);
isForm.isText.focus();
}

navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);

</script>
<style type="text/css">

body {background-color:#eae3c6;margin-top:60px}

</style>
</head>
<body>
<form action="">
<table align='center' cellspacing='0' cellpadding='2' style='border:1px solid black;font-family:arial;font-weight:bold;font-size:12pt;width:200px;height:110px;background-color:#ffffe0'>
<thead>
<tr>
<th colspan='2' height='25' bgcolor='#add8e6'>
Name List
</th>
</tr>
</thead>
<tbody>
<tr>
<td align='right' style='font-size:11pt'>
Trim At:
</td>
<td>
<input type='text' name='isText' size='15' onkeyup="buildSmartOptions(this.form)">
</td>
</tr>
<tr>
<td align='center' colspan='2'>
<select name='isList' onchange="getChoice(this.value)" style='width:151px'>
<option selected value='null'>
Make a Selection
</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Henley
03-14-2009, 12:06 AM
Of course, I could be wrong.

You may want to look at this AJAX "suggest" example:

http://www.w3schools.com/ajax/ajax_example_suggest.asp

Deadeye
03-14-2009, 12:11 AM
All my code is based on their code :P

The point now is to take the names and put them into a combo box instead of having them in just a long line.

Henley
03-14-2009, 12:14 AM
Yes, I understand.

But, you already know how to split the string on commas.

Take that array, and use my code, the function buildList(), to populate the select list.

But, you'll have to delete the previous options, by putting this line at the top of the function:

isForm.isList.options.length = 0 // or 1 if there's a "Make a selection" option at the top of the list.

Make sense?

Deadeye
03-14-2009, 12:31 AM
Yes makes sense, didn't notice your post with the code for some reason, sorry about that.

But I will have to resume tomorrow since I'm having the toughest time staying awake, stupid sleep. Thanks for the help and I will post here again either with a question or solved code tomorrow. Lets hope for the ladder.

Henley
03-14-2009, 12:37 AM
Same here. I'll look at this thread later this weekend.

I believe you'll solve it, though. You're code isn't that of a novice.

Deadeye
03-15-2009, 12:47 PM
Well this is how it looks now

HTML:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Auto Load Form</title>
<link rel='stylesheet' type='text/css' href='styles.css' />

<script type='text/javascript' src="suggestion.js">

</script>

</head>
<body>
<form>

<div>
<div><h1>Ajax Auto Load Form</h1></div>
<div><br></div>
<div>Type inn a name: </div>
<div>
<div><input name='isText' type="text" id="txt1" size='20' onkeyup="Worker(this.value,this.form)" /></div>
</div>


<p>Suggestions: <span id="Sugestion"></span></p>

<select name='isList' onchange="getChoice(this.value)" style='width:151px'>
<option selected value='null'>
Make a Selection
</option>
</select>

</div>

</form>
</body>
</html>


JAVASCRIPT:


var x;

function Worker(str,isForm)
{
x = isForm;

if (str.length < 3)
{
document.getElementById("Sugestion").innerHTML="Ekki ngu langt";
return;
}
else if(str.length >=3)
{
xmlHttp=createXmlHttpRequestObject();

if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
else
{
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
}
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
var smartOptions = [];
var myString = xmlHttp.responseText;
var mySplitResult = myString.split(" , ");

buildSmartOptions(x);


navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
//document.getElementById("Sugestion").innerHTML=mySplitResult;
//document.getElementById("Sugestion").innerHTML=xmlHttp.responseText;
}
}

function buildList(x,nArray){

for (i=0; i<nArray.length; i++)
{
nOption = document.createElement('option');
isData = document.createTextNode(nArray[i]);
nOption.setAttribute('value',nArray[i]);
nOption.appendChild(isData);
x.isList.appendChild(nOption);
}
}

function buildSmartOptions(x){

matchStr = x.isText.value.toLowerCase();
if (matchStr != "")
{
smartOptions.length = 0;
n = 0;
endClip = matchStr.length;
for (i=0; i<mySplitResult.length; i++)
{
if (matchStr == mySplitResult[i].slice(0,endClip).toLowerCase())
{smartOptions[n++] = mySplitResult[i]}
}
x.isList.length = 1;
for (i=0; i<smartOptions.length; i++)
{
buildList(x,smartOptions);
}
if (smartOptions.length > 5){x.isList.size=6}
else {x.isList.size = smartOptions.length+1}
}
if (matchStr == ""){init()}
}

function getChoice(isChoice){

alert(isChoice);
}






//g veit a g meira og minna copy+paste aferina sem sndir okkur en hn var bara svo g :)
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp=null;
// this should work for all browsers except IE6 and older
try
{
// try to create XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE6 or older
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
// try every prog id until one works
for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
{
try
{
// try to create XMLHttpRequest object
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e) {}
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}


It seems to never get to readyState==4 it is just stuck at zero.
I should mention that I'm pretty green to the whole AJAX buisness so any info on what to do next would be great help.

PS. I know I just copy and pasted your code but I always do that and then modify it to fit my enviorment and then I trim it and put comments in.

Deadeye
03-15-2009, 05:20 PM
Ok I think this is done, here is what the final product looks like.

Suggestion.js


var x;

function Worker(str,isForm)
{
x = isForm;
if(str == "")
{
init()
}
if (str.length < 3)
{
init()
return;
}
else if(str.length >=3)
{ //Br til createXmlHttpRequestObject.
xmlHttp=createXmlHttpRequestObject();

if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
else
{
//Slin ar sem nfnin eru geymd
var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
//egar a er allt komi checkar forriti hvort onreadystatechange er jafnt og 4
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
}
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
//Ef readystate er jafnt og 4 keyrir hn buildSmartOptions
buildSmartOptions(x);
}
}


function buildList(x,nArray)
{

for (i=0; i<nArray.length; i++)
{
nOption = document.createElement('option');
isData = document.createTextNode(nArray[i]);
nOption.setAttribute('value',nArray[i]);
nOption.appendChild(isData);
x.isList.appendChild(nOption);
}
}

function buildSmartOptions(x)
{

matchStr = x.isText.value.toLowerCase();
if (matchStr != "")
{

var smartOptions = [];
var myString = xmlHttp.responseText;
var mySplitResult = myString.split(" , ");

if(mySplitResult.length == 0)
{ alert('hello');}

smartOptions.length = 0;
n = 0;

endClip = matchStr.length;

for (i=0; i<mySplitResult.length; i++)
{
if (matchStr == mySplitResult[i].slice(0,endClip).toLowerCase())
{
smartOptions[n++] = mySplitResult[i]
}
}

x.isList.length = 1;

for (i=0; i<smartOptions.length; i++)
{
buildList(x,smartOptions);
}

if (smartOptions.length > 5)
{
x.isList.size=6
}
else
{
x.isList.size = smartOptions.length+1
}
}

if (matchStr == "")
{
init();
}
}

function init()
{
ValueDIV.innerHTML = "";
x.isList.options.length = 1;
x = document.forms[0];
x.isList.length = 1;
x.isList.size = 1;
allOptions.sort();
buildList(x,allOptions);
x.isText.focus();
}

function getChoice(isChoice)
{
ValueDIV = document.getElementById("ValueDIV");
if(isChoice != "Type In A Name")
{
ValueDIV.innerHTML = isChoice;
}
else
{
ValueDIV.innerHTML = "";
}
}






//g veit a g meira og minna copy+paste aferina sem sndir okkur en hn var bara svo g :)
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp=null;
// this should work for all browsers except IE6 and older
try
{
// try to create XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE6 or older
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
// try every prog id until one works
for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
{
try
{
// try to create XMLHttpRequest object
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch (e) {}
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}


Index.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Auto Load Form</title>
<link rel='stylesheet' type='text/css' href='styles.css' />

<script type='text/javascript' src="suggestion.js">

</script>

</head>
<body>
<form>

<div>
<div><h1>Ajax Auto Load Form</h1></div>
<div><br></div>
<div>Type inn a name: </div>
<div>
<div><input name='isText' type="text" id="txt1" size='20' onkeyup="Worker(this.value,this.form)" /></div>
</div>

<div>
<p>
<select name='isList' onchange="getChoice(this.value)" style='width:151px'>
<option selected>
Type In A Name
</option>
</select>
</p>
</div>
</div>

<div id="ValueDIV" />

</form>
</body>
</html>


Everything else has stayed the same, and it should be 100% usable.
Thanks for all the help.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum