Pass Variable To Auto Complete JavaScript - javascript

I have this basic auto complete JavaScript that works well, but you need to hard code the web page. What I'm trying to do is send the "Autocomplete" variable data to the page using a Perl script
The working JavaScript code looks like this:
var CustomArray = new Array('an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfisher',
'kingpin','SML');
Now the new code is:
var CustomArray=new Array(Autocomplete);
And the Perl script is sending back the data to the browser looking like this:
var Autocomplete = 'an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfish er','kingpin','SML'
I also tried
var Autocomplete = ['an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfisher',
'kingpin','SML']
But I get: 'an apple','alligator','elephant','pear','kingbird','kingbolt','kingcraft','kingcup','kingdom','kingfish er','kingpin','SML' All as one string in the auto complete.
I cant seem to get it to work right. Full HTML code is below.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://www.comicinvasion.com/Code/Java/Autocomplete/Autocomplete.js"></script>
<script language="javascript" type="text/javascript" src="http://www.comicinvasion.com/Code/Java/Autocomplete/Common.js"></script>
<script language="JavaScript1.2" type="text/javascript" src="http://www.ComicInvasion.com/cgi-bin/Autocomplete.pl"></script>
<script>
var CustomArray=new Array(Autocomplete);
</script>
</head>
<body>
<input type='text' style='font-family:verdana;width:300px;font-size:12px' id='ACMP' value=''/>
<script>
var obj = actb(document.getElementById('ACOMP'),CustomArray);
</script>
</body>
</html>

First, it looks like there is a typo. The id of your input element is ACMP whereas you pass 'ACOMP' to getElementById.
Second, you do not provide the source code for your Perl script. It might look like this:
#!/usr/bin/perl
use utf8;
use strict; use warnings;
use CGI();
local $| = 1;
print CGI::header(
-type => 'text/javascript',
-charset => 'utf-8',
);
print <<JS;
var Autocomplete = [
'an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfisher',
'kingpin','SML'
];
JS
With the following HTML, autocompletion works:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="http://www.comicinvasion.com/Code/Java/Autocomplete/Autocomplete.js"></script>
<script type="text/javascript" src="http://www.comicinvasion.com/Code/Java/Autocomplete/Common.js"></script>
<!-- Replace with the URI of your script -->
<script type="text/javascript" src="http://test:8080/cgi-bin/autocomplete.pl"></script>
</head>
<body>
<input type='text'
style='font-family:verdana;width:300px;font-size:12px'
id='ACOMP' value=''>
<script type="text/javascript">
var obj = actb(document.getElementById('ACOMP'), Autocomplete);
</script>
</body>
</html>
Finally, I find it curious that your JavaScript files live in a directory called Java.

Have the perl script return this:
var CustomArray = "an apple, alligator".split(',');
Or, if it has to be this it's okay too:
var CustomArray = "'an apple','alligator'".split(',');
Obviously, I omitted the rest of the items in there but you'd include all of them.

Related

How to load different html files in QUnit?

I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}

How do I pass this JSON data to an autocomplete

Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!
NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>
why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?
There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});
Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/

Issue with wisdom generator

I am trying to display random wisdom on a web page but I cannot figure out why the code below does not work.
Thank you
My javascript external file is:
function random(low, high) {
return Math.floor(Math.random()*(high-low+1)) + low;}
function randomarr() {
var arr = new Array("...1", "...2", "...3");
return arr[random(0, arr.length-1)];}
function display(){
var k = randomarr();
alert(k);}
and my html file
In the head section I've got:
<script type="text/javascript">
src="java.js"
</script>
And in the body section I've got:
<p>
<script type="text/javascript">
document.write(display());
</script>
</p>
The syntax for including the script in the <head> is wrong. Try this:
<script type="text/javascript" src="java.js"></script>

How to remove <script> tags from an HTML page using C#?

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
</head>
</html>
Is there a way in C# to modify the above HTML file and convert it into this format:
<html>
<head>
</head>
</html>
Basically my goal is to remove all the JavaScript from the HTML page. I don't know what is be the best way to modify the HTML files. I want to do it programmatically as there are hundreds of files which need to be modified.
It can be done using regex:
Regex rRemScript = new Regex(#"<script[^>]*>[\s\S]*?</script>");
output = rRemScript.Replace(input, "");
May be worth a look: HTML Agility Pack
Edit: specific working code
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string sampleHtml =
"<html>" +
"<head>" +
"<script type=\"text/javascript\" src=\"jquery.js\"></script>" +
"<script type=\"text/javascript\">" +
"if (window.self === window.top) { $.getScript(\"Wing.js\"); }" +
"</script>" +
"</head>" +
"</html>";
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(sampleHtml));
doc.Load(ms);
List<HtmlNode> nodes = new List<HtmlNode>(doc.DocumentNode.Descendants("head"));
int childNodeCount = nodes[0].ChildNodes.Count;
for (int i = 0; i < childNodeCount; i++)
nodes[0].ChildNodes.Remove(0);
Console.WriteLine(doc.DocumentNode.OuterHtml);
I think as others have said, HtmlAgility pack is the best route. I've used this to scrape and remove loads of hard to corner cases. However, if a simple regex is your goal, then maybe you could try <script(.+?)*</script>. This will remove nasty nested javascript as well as normal stuff, i.e the type referred to in the link (Regular Expression for Extracting Script Tags):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
<script> // nested horror
var s = "<script></script>";
</script>
</head>
</html>
usage:
Regex regxScriptRemoval = new Regex(#"<script(.+?)*</script>");
var newHtml = regxScriptRemoval.Replace(oldHtml, "");
return newHtml; // etc etc
This may seem like a strange solution.
If you don't want to use any third party library to do it and don't need to actually remove the script code, just kind of disable it, you could do this:
html = Regex.Replace(html , #"<script[^>]*>", "<!--");
html = Regex.Replace(html , #"<\/script>", "-->");
This creates an HTML comment out of script tags.
using regex:
string result = Regex.Replace(
input,
#"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|\n|\s)*?>",
string.Empty,
RegexOptions.Singleline | RegexOptions.IgnoreCase
);

Trying to parse xml file for javascript quiz

I am trying to create a javascript quiz, that gets the questions from a xml file. At the moment I am only starting out trying to parse my xml file without any success. Can anyone point me to what I am doing wrong?
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<div class="spmArr">
</div>
<script type="text/javascript">
var quizXML = '<quiz><Sporsmal tekst="bla bla bla"/><alternativer><tekst>bla</tekst><tekst>bli</tekst><tekst correct="yes">ble</tekst></alternativer><Sporsmal tekst="More blah"/><alternativer><tekst>bla bla</tekst><tekst correct="yes">bli bli</tekst><tekst>ble ble</tekst></alternativer></quiz>'
var quizDOM = $.xmlDOM( quizXML );
quizDOM.find('quiz > Sporsmal').each(function() {
var sporsmalTekst = $(this).attr('tekst');
var qDiv = $("<div />")
.addClass("item")
.addClass("sporsmal")
.appendTo($(".spmArr"));
var sTekst = $("<h2/>")
.html(sporsmalTekst)
.appendTo(qDiv);
});
</script>
</body>
</html>
When I try this in my browser the classes and div are not being created. And the page is just blank. Am i doing something wrong when I intialize the xml?
edited to add prototype.js and close function
Looks like you're forgetting to close your .each call. append ); after the statement for sTekst and your call will parse correctly.

Categories