JavaScript DOM coding - 'undefined' error - javascript

I am having problem with this error:
'undefined' is null or not an object'
Can you please have a look and let me know. In my coding, I want to have simple DOM JavaScript code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
init();
function init()
{
getElementByTabIndex("4", "submit")[0].addEventListener("click", Verify, false);
}
function Verify() {
alert('done');
// all verification code will be here...
}
function getElementByTabIndex(index, type, node)
{
if (!node)
{
node = document.getElementsByTagName('body')[0];
}
var a = [];
els = node.getElementsByTagName('*');
for (var i = 0, j = els.length; i < j; i++)
{
if (els[i].tabIndex == index && els[i].type == type)
{
a.push(els[i]);
}
}
return a;
}
</script>
<body>
<input type="email" id="email" /><input type="password" id="pass" /> <label class="Login" for="login"><input value="Log In" tabindex="4" type="submit" id="login"></label>
</body>
</html>

You have to move you code at bottom or call init() after body is loaded.
Reason: you are trying to get elements even before they exists.
Eg :
<head>
<script>
var elm= document.getElementById('id');
//this will be always undefied, as trying to read element even before they exist
</script>
</head>
<body>
<div id='foo'></div>
<script>
var elm= document.getElementById('id');
//this wont be undefined
</script>
</body>

You call:
if (!node) {
node = document.getElementsByTagName('body')[0];
}
But your script runs before the DOM has finished loading, and so the body tag does not exist.
So node is undefined, and when you attempt the following, you get your error:
node.getElementsByTagName('*');
Run init() on document load, instead of immediately.
PS. jsfiddle and Firebug allowed me to debug this very quickly.

'body' isn't available to javascript at the time you are trying to call init().
call your init method when the dom has finished loading, like so:
window.onload = function (){
init();
}
note that in order to make this work across browsers (if you plan on using it outside your planned Safari extention) you will have to do some extra work. more info: http://www.javascriptkit.com/dhtmltutors/domready.shtml

Related

Difference between onclick and click using id JavaScript jQuery

I have been learning javascript and jquery for short period. I even know that the jquery is a library for the javascript. Now, I made a sample work on both and want to know the difference between the actions. Here is my code :
$(document).ready(function() {
$("#buttonOne").click(function() {
document.getElementById('paragraph').innerHTML = "You are yet to perform";
})
});
function checkButton() {
alert("Hello There");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="buttonOne" onClick="checkButton()">Click Me and Understand</button>
<p id="paragraph"></p>
index.html
<!DOCTYPE html>
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Wifi Wizard</title>
</head>
<body>
<br>
<br>
Start Wifi <input type="button" value="wifi" name="Wifi" id="wifi"/> <br>
Search Wifi <input type="button" value="search" name="Search" id="search"/> <br>
Scan Wifi <input type="button" value="scan" name="Scan" id="scan"/> <br>
<div id = "dataTable">
</div>
<input type = "password" name = "password" id = "passValue"></input>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
app.js
$(document).ready(function() {
$("#passValue").hide();
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
$('#wifi').click( function()
{
try {
WifiWizard.isWifiEnabled(win, fail);
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
function win(e) {
if(e) {
alert("Wifi enabled already");
}
else {
WifiWizard.setWifiEnabled(true, winEnable, failEnable);
}
}
function fail(e) {
alert("Error checking Wifi status");
}
function winEnable(e) {
alert("Wifi enabled successfully");
}
function failEnable(e) {
alert("Error enabling Wifi ");
}
$('#search').click( function()
{
try {
WifiWizard.listNetworks(listHandler, fail);
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
function listHandler(a){
alert(a);
}
$('#scan').click( function()
{
try {
WifiWizard.getScanResults({numLevels: 1},listHandler1, fail);
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
function listHandler1(a) {
alert(JSON.stringify(a));
var network_array = [];
var content = "<table>"
for (i = 0; i < a.length; i++) {
content += '<tr><td><button onclick="clickWifi(\'' + a[i].SSID + '\');">' + network_array.push(a[i].SSID) + '</button></td></tr>';
}
content += "</table>"
alert(network_array);
$('#dataTable').append(content);
}
function clickWifi(ssid) {
alert("Hello");
var networkSSID = ssid;
$("#passValue").show();
var passWord = document.getElementById("passValue");
var config = WifiWizard.formatWPAConfig(networkSSID, passWord);
}
WifiWizard.addNetwork(config, function() {
WifiWizard.connectNetwork(networkSSID, connectSuccess, connectFailed);
});
}
For above scenario, I have a made a button to call its click function dynamically, so please help as I have no idea whether the button declared is correct or wrong.
Here I have made a click function using id in jquery and onclick function using javascript. But the alert first pops up and then the jquery does it's work. I would like to know why doesn't jquery go first. Please give a suggestion.
https://jsfiddle.net/m3prjL8q/
here is the answer to the question in the comments. As far as the original post goes, it was answered in the comments, there is no need to repeat that.
When you use $(document).ready(function(){}) what you are doing is actually creating an event listener that will 'trigger' once the document is ready and giving it a handler function. This is yourJQuery function in the example. If you declare a function within the handler, this function is not accessible to the native javascript outside of the handler.
function yourJQuery(){
function innerDeclare(){
alert("I cannot be accessed outside of yourJQuery function");
}
}
innerDeclare();
IF i understood your Question correctly you want to know why html onclick method runs before jQuery click method.
That is simply because sequence you are adding click event on element.
HTML onclick method does not wait for DOM to render and attach event directly to the element.
But your jQuery method waiting for for Dom to be ready then it goes and attach the click event to element.
Hence events are getting executed in sequence.
For better performance, use the native JavaScript. For faster development, use jQuery. Check the comparison in performance at jQuery vs Native Element Performance.

Pop-up based on location (Specifically the UK)

I have a very internationalised website, however I need to produce a pop-up specifically for our UK customers.
What I require is:
On page load: Is the user from the UK?
If yes then show div.
Else
Div remains hidden.
You can do this using freegeoip.
Since you mentioned that you want to use plain JavaScript (not jQuery), you should use JSONP to get the country:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>UK localisation</title>
</head>
<body>
<div id="myDiv" style="display:none">
<h1>Kittens</h1>
</div>
<script>
function toggleDiv(content) {
console.log(content.country_code);
if(content.country_code === 'GB') //Or GBR, or UK, I'm not sure.
{
document.getElementById('myDiv').style.display = "inline";
}
else
{
alert("You are not from UK, you are from " + content.country_code);
document.getElementById('myDiv').style.display = "none";
}
}
window.onload = function()
{
// create script element
var script = document.createElement('script');
// passing src with callback name
script.src = 'http://freegeoip.net/json/?callback=toggleDiv';
// insert script to document and load content
document.body.appendChild(script);
}
</script>
</body>
</html>

How to take this string from user at run time?

Look at the below code, this JavaScript is used to take a string (in a language other than English) and convert it into English.
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var content = document.getElementById('translation');
// Setting the text in the div.
content.innerHTML = '<div id="text">HELLO WORLD<\/div>
<div id="translation"/>';
// Grabbing the text to translate
var text = document.getElementById("text").innerHTML;
// Translate from Spanish to English, and have the callback of
// the request put the resulting translation in the
// "translation" div. Note: by putting in an empty string for
// the source language ('es') then the translation will
// auto-detect the source language.
google.language.translate(text, '', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
</script>
I want that the string "HELLO WORLD" must be entered by user at run time in a text field and then that string is passed to the div id text. So is this possible?
Hope you are referring to the document below:
http://code.google.com/apis/language/translate/v1/getting_started.html
Please refer to the section "Getting Started" where it says about "Signing up for an API key". This needs to be done before you could implement the code in your page.
Once done, make the modification to the script file which you include in the html page with your key.
Here, replace your key with "MY_KEY_STRING" in the bottom code and get started.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Language API Sample</title>
<script src="https://www.google.com/jsapi?key=MY_KEY_STRING"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
//Show the translate button
document.getElementById("translateButton").style.display = "";
}
google.setOnLoadCallback(initialize);
function translate() {
var text = document.getElementById("fromText").value;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("toText");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
From:<input type="text" id="fromText"/>
To:<span id="toText"></span>
<input type="button" value="Translate" onclick="translate()" style="display: none;" id="translateButton">
</body>
</html>
HTML:
<form id="translate">
<textarea id="translate-me"></textarea>
<input type="submit" />
</form>
JavaScript:
var form = document.getElementById('translate')
var textarea = document.getElementById('translate-me')
form.onsubmit = function () {
google.language.translate(textarea.value, ...)
return false; // prevent default action (form submission)
}
Using jQuery or something similar would make this easier, of course.

document.title problems ie8

Why does IE8 fail to change the documents title with document.title="test title";
Following works on IE8 for me. But I did get the ActiveX security popup, so perhaps your IE8 is not set to prompt for these issues and just deny scripting.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test</title>
<script type="text/javascript">
function changeTitle() {
document.title = 'Foobar';
}
</script>
</head>
<body onload="changeTitle()">
</body>
</html>
Really? Using document.title = 'Foo Bar'; has always worked for me. Is your script even executing?
Try shoving this right before the document.title = ...:
alert('I work.');
If you don't get an alert box, your script isn't even running.
found this:
http://support.microsoft.com/kb/296113
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
function runTest()
{
var s ="We should set this as the new title"
var mytitle = document.createElement("TITLE");
mytitle.innerHTML = s;
alert(s);
document.documentElement.childNodes[0].appendChild(mytitle);
}
function fix()
{
var s = "Now we change the title";
alert(s);
document.title = s;
}
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="Problem" onclick="runTest()"/>
<input type="button" value="Workaround" onclick="fix()"/>
</BODY>
for me this is works in IE 9,8,7
maybe you dont call your function, or there is something which not works.
the document.title must work!

Ajax not working

The code provided below doesn't show all the content of that page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript">
var rootdomain="http://"+window.location.hostname
alert(rootdomain);
function ajaxinclude(url) {
var url=rootdomain+url;
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously
page_request.send(null)
writecontent(page_request)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 ||
page_request.status==200)
document.getElementById("write").innerHTML=page_request.responseText;
}
</script>
</head>
<body>
<div id="write">
</div>
<input type="button" value="Submit !" onclick="ajaxinclude('/songcake/index.php');"/>
</body>
</html>
Please Help
Thanks.
You need to add a closure that reacts upon the completion of the document loading process.
page_request.onreadystatechange = function() {
if(page_request.readystate == 4) {
// data handling here
}
}
As pointed out though, using jQuery will make things a lot easier.
Edit: To clarify, your AJAX call does check for the connection status (request.status), but not for the loading status (request.readystate). Your document probably did not load completely.
Here's a reference for the W3.org XMLHTTPRequest API: http://www.w3.org/TR/XMLHttpRequest/ .
Edit2: Btw, an <iframe> element would solve your problem with a lot less code.
Edit 3: Code
function ajaxinclude(url) {
//...
page_request.open('GET', url, false) //get page synchronously
//<> add onreadystatechange handler
page_request.onreadystatechange = function() {
if(page_request.readystate === 4) {
if(page_request.state === 200) {
//call function on success
writecontent(page_request.responseXML)
}
}
}
page_request.send(null)
}
Some additions:
if you put your ajax call into the <HEAD> you need to either create the dom elements you want to append data to as they are not available when the runtime runs through (which might lead to a dom error); or you need to add an on dom load event handler.
Synchronous calls are not properly implemented in some browsers and this might lead to errors too.
Why you should not use jQuery? You can do this simple as below..
$("#write").load("/songcake/index.php");
[EDITED]
Below you can see the completed code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src='scripts/jquery.js'></script>
</head>
<body>
<div id="write">
</div>
<input type="button" value="Submit !"
onclick="$('#write').load('/songcake/index.php');"/>
</body>
</html>
You can download jQuery from here : http://jquery.com/
The source for my answer you can find here : http://api.jquery.com/load/
try to use FireBug
FireBug show you state of your request.
If it 200 and you see that in reqest answer (in firebug) broken data then
you should check your index.php script

Categories

Resources