EDIT
Thank you all for your assistance. I have made the modifications to the script, with try and catch (err), however, i still do not get the alert when the code is run. I've also replaced "studentInfo[i].getElementsByTagName("id")[i].childNodes[i].nodeValue" with "studentInfo[i].getElementsByTagName("id")[0].childNodes[0].nodeValue" as well as all similar references, except now, it won't even return the first loop. It seems to be exiting the function before it hits "catch" for some reason.I've marked the changes in bold.
I know this has been posted quite a bit on this site, but none of the answers seem to quite be able to help me. I have a for loop that stops iterating after the first loop. The data from the first loop is correct, but I need it to keep looping through. I've used a couple different lint tools and they say my code is valid, so I must be forcing it to exit the loop some how. Someone help me figure out what I'm doing wrong, please.
<html>
<head>
<title>Tardy Reporting</title>
<script type="text/javascript" src="students.js">
</script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" id="idForm" />
<input type="text" name="idNumber" id="idNumber"/>
<input type="button" name="Search" value="Search" onClick="getId(document.idForm.idNumber.value);" />
</form>
<br></br>
<div id="div1"></div>
<p>
</body>
</html>
var ajxObj;
if(window.XMLHttpRequest){
ajxObj = new XMLHttpRequest();
}
else{
ajxObj = new ActiveXObject('Microsoft.XMLHTTP');
}
ajxObj.open("GET","studentbase.xml",false);
ajxObj.send();
xmlData = ajxObj.responseXML;
var studentInfo = xmlData.getElementsByTagName("student");
function getId(studentId) {
**try{**
for(var i = 0; i < studentInfo.length; i++) {
if(studentId == **studentInfo[i].getElementsByTagName("id")[0].childNodes[0].nodeValue || studentId === studentInfo[i].getElementsByTagName("name")[0].childNodes[0].nodeValue**){
document.getElementById('div1').innerHTML=(studentInfo[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
}
else {
document.getElementById('div1').innerHTML="Error: Not Found"
}
}
**}catch (err){
alert(err.ToString());
}**
}
<?xml version="1.0" encoding="UTF-8" ?>
<thebase>
<student>
<id>50011234</id>
<name>Mike Simpson</name>
<grade>n/a</grade>
<teacher>George Washington</teacher>
<tardies>0</tardies>
</student>
<student>
<id>50012345</id>
<name>Greg Pollard</name>
<grade>n/a</grade>
<teacher>Darth Vadar</teacher>
<tardies>0</tardies>
</student>
<student>
<id>50013456</id>
<name>Jason Vigil</name>
<grade>n/a</grade>
<teacher>Obi Wan Kenobi </teacher>
<tardies>0</tardies>
</student>
</thebase>
I suspect your code is throwing an error and you are not aware of this. I suspect the reference "studentInfo[i].getElementsByTagName("id")[i].childNodes[i].nodeValue" should be "studentInfo[i].getElementsByTagName("id")[0].childNodes[0].nodeValue".
Try putting a "try...catch" around the "for" loop, like so:
function getId(studentId) {
try {
for(var i = 0; i < studentInfo.length; i++) {
if (studentId == studentInfo[i].getElementsByTagName("id")[i].childNodes[i].nodeValue || studentId === studentInfo[i].getElementsByTagName("name")[i].childNodes[i].nodeValue){
document.getElementById('div1').innerHTML=(studentInfo[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
}
else {
document.getElementById('div1').innerHTML="Error: Not Found"
}
}
} catch (err) {
alert(err.ToString());
}
}
There needed to be three equal signs (ie. "===") in the if statement.
Related
I have an array in js, and want user to check if his product number exist in array. Code is:
var arr = ['3bktzgo4',
'2ltold4k',
'l4u93l4r'];
function check() {
var input = document.getElementById("Input").value;
for (i = 0; i < arr.length; i++) {
if (arr[i] == input) {
alert("congratulations! Product code found! Your product is original!");
return;
}
}
alert("Product code not found! Your product is counterfeit!");
};
<div>
<button onclick="beginhere()">Search</button>
<input id='Input'>
</div>
<html !DOCTYPE html>
<head>
</head>
<body>
<script>
var arr = ['3bktzgo4',
'2ltold4k',
'l4u93l4r'];
function check() {
var productNumber = document.getElementById("productNumberId").value;
console.log(productNumber);
if(arr.indexOf(productNumber) != -1)
return alert("congratulations! Product code found! Your product is original!");
return alert("Product code not found! Your product is counterfeit!");
};
</script>
<div>
<button onclick="check()">Search</button>
<input id='productNumberId'>
</div>
</body>
</html>
I have created this snippet and would like you to know what mistakes or changes you need to make in your code.
Do not use words like "input" for variable names or ids, use words that can describe the value it stores.
The "check" function was never called and it should have replaced the "beginhere" function since this function was never defined.
You did not enclose your javascript code inside the <script> tag (read more about the important tags in HTML).
Read about the useful functions in javascript like "indexOf", "splice", "push", "pop", etc that can help reduce your code or/and complexity.
I have written a script that validates username submitted through form. If the user name is greater than 5 characters, it should show some message to the user.
The error that I'm getting is
:Uncaught TypeError: Cannot read property 'length' of undefined
at checkusername (eventobject.html:24)
at HTMLInputElement. (eventobject.html:18)
I have used 'blur' event.
the code is :
<html>
<head>
</head>
<body>
<form>
<label for="text">Username:</label>
<input type="text" id="text" />
<p id="para"></p>
</form>
<script>
var el=document.getElementById("text");
el.addEventListener('blur',function(){checkusername(5);},false);
var msg=document.getElementById("para");
function checkusername(min)
{
if(this.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
</script>
</body>
</html>
The above code works fine when I write the same event handler without parameters.
the code for event handling without passing parameters is shown below:
<html>
<head>
</head>
<body>
<form>
<label for="text">Username:</label>
<input type="text" id="text" />
<p id="para"></p>
</form>
<script>
var el=document.getElementById("text");
el.addEventListener('blur',checkusername,false);
var msg=document.getElementById("para");
function checkusername()
{
if(this.value.length<5)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
</script>
</body>
</html>
You can use Function.prototype.bind() to set this at first parameter and parameters to be used within function body passed at second through N parameters to .bind()
el.addEventListener('blur',checkusername.bind(el, 5 /*, N */),false);
After doing some research on the way events are called,I came across two solutions to the above problem.
Have a look at the error message again:-
:Uncaught TypeError: Cannot read property **'length'** of undefined at **checkusername**
It is clear from the above message that error is occurring inside the checkusername() function. And the actual error is happening because length is applied on undefined variable, in this context,this.
The reason for why this is undefined in this event call:
1.In regular function call(as shown below), the keyword this is associated with the event on which the function is called.
el.addEventListener('blur',checkusername(),false); //call without parameters
Here,event is calling the function checkusername() directly.In short, this is holding reference to el i.e.., this-->el.
In this kind of event call, it makes sense to use length property on this because it is holding something.
2.In the function call that involves passing parameters(problem in the question),the regular function call is not supported as per JavaScript standard. JavaScript defines that the function call needs to be embedded inside a anonymous function(as shown below):
el.addEventListener('blur',function(){checkusername(5);},false); //call with parameters.
Here,event is calling the anonymous function and which in-turn calls the checkusername(). Hence,this does not refer to anything,undefined.Therefore, calling length on this inside checkusername returns error.
since, this cannot be used, the following techniques are used.
method 1:: Passing el as part of parameters list.
var el=document.getElementById("text");
el.addEventListener('blur',function(){checkusername(el,5);},false);
var msg=document.getElementById("para");
function checkusername(el,min)
{
if(el.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
method 2: Declaring el globally.
var el=document.getElementById("text");
el.addEventListener('blur',function(){checkusername(5);},false);
var msg=document.getElementById("para");
function checkusername(min)
{
if(el.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
Found these solutions in Javascript&JQuery book by Jon Duckett..
useful link
Hope this was helpful. :) My first answer in stackoverflow.
Try this -
<!DOCTYPE html>
<html>
<body>
<form>
<label for="inputText">Username:</label>
<input type="text" id="inputText" />
<p id="message"></p>
</form>
<script>
var el=document.getElementById("inputText");
el.addEventListener('blur',function(){checkusername(5);},false);
var msg=document.getElementById("message");
function checkusername (min) {
if(this.el.value !== (undefined || null) && this.el.value.length < min) {
msg.textContent="username less than 5 characters";
} else {
msg.textContent='';
}
}
</script>
</body>
</html>
You can try this.
I hope it's will work.
<html>
<body>
<form>
<label for="text">Username:</label>
<input type="text" id="text" />
<p id="para"></p>
</form>
<script>
let element=document.getElementById("text");
element.addEventListener('blur',function(){checkusername(5);},false);
let msg=document.getElementById("para");
function checkusername(min)
{
if(element.value.length<min)
{
msg.textContent="username less than 5 characters";
}
else
{
msg.textContent='';
}
}
</script>
</body>
</html>
I am tryint to create a little RadioPlayer that works online . Now this is the JavaScript Code that i have
function changeLink(link)
{
/* this changes the link and plays the radio*/
var radio= document.getElementById("radio");
radio.src = link;
radio.play();
}
function jsonLoad()
{
var xmlhttp = new XMLHttpRequest();
var url = "playList.txt";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
readJSON(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function readJSON(obj)
{
var list = "<ui>";
for (var i = 0; i < obj.length ; i++)
{
list += "<li><a href='javascript:changeLink(" +"\"" + obj[i].radioLink + "\"" +");'>" + obj[i].name + "</a></li>";
}
list += "</ui>";
document.getElementById("radioLoad").innerHTML = list;
}
Also this is the HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> My Radio Player</title>
<script src="Script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="jsonLoad()">
<p>This is the link that i will change his property</p>
<audio id="radio" src="#" controls autoplay preload="auto" ></audio>
</audio>
<br>
<p id="radioLoad">
</p>
</body>
Things is that locally the JSON File is perfectly working, and the webpage shows as i expected. When i put it on a server though, it's like the JSON file is not loaded and the other fuction (readJSON(myArr);) is not fired. Seems that there is something wrong with the IF Condition but i don't know excatly why. Can somebody help me?
EDIT: Seems that the code only works locally in Google Chrome. In internet explorer the links are generated but they don't play the radio when i click on them. Also on the iphone simulator that i tested, the audio tag is not working properly. I will try on different webbrowsers also.
EDIT2: it works now. I managed to figure outthe issue. It was nothing wrong with the code, it was with the server i was hosting on. So i changed the web hoster and now it works. You can see it here:
http://radioplay4all.16mb.com/
Thank you anyway :)
Without debugging it myself I can't be sure, but I'm pretty sure that your problem is in your readJSON() function, when you try to get the .length property of an object (JSON.parse() returns a javascript object), since objects don't have a .length property. To find the number of keys an object has, you could use Object.keys(myArr).length. So in your for loop, obj.length is Null, so i can't be less than Null, so it doesn't execute. So if you replace i < obj.length with i < Object.keys(obj).length that should fix the problem.
I'm trying to learn basic HTML and Javascript, and am not sure what is wrong with this code. It is probably a very simple error and I'm sorry if it is. When I try clicking the buttons, Chrome says in the console that "correct" and "incorrect" are not defined, but I have checked the syntax for the functions and I can't see what is wrong. Thanks for your help :)
<!DOCTYPE html>
<html>
<head>
<title>Question 1</title>
</head>
<body>
<p>Q1: What is the height of the Eiffel Tower?</p>
<br>
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!
<br>
Next Question";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!
<br>
Next Question";
}
</script>
<button onclick="incorrect()">767m</buttton>
<br>
<button onclick="incorrect()">442m</button>
<br>
<button onclick="correct()">324m</button>
<br>
<button onclick="incorrect()">278m</button>
<p id="feedback"></p>
</body>
You have confusing ""(double quotes) in the innerHTML strings. Try this:
instead of "q2.htm" use 'q2.htm'
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
If you look at the console log in Chrome (press F12 to enter Developer Tools where you can see the log), you will see an error message “Unexpected token ILLEGAL”. The reason is that you have line breaks inside a JavaScript string, which is not permitted, so the function definitions fail in parsing. Moreover, you are using quotes inside a quoted string, which isn’t permitted either. Use single quotes (') as inner quotes or (in this case) just omit them, e.g.
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href=q2.htm>Next Question</a>";
}
This works:
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
You have to put them on the same line or use concatenation.
I made a puzzle game using HTML5, just now I tried to add local storage to the game, but failed.
I wrote three functions. The problem is: If I put all the functions in one .js file, none is defined when debugging(via chrome). If I split these three functions to another file and add a tag to the .html file, I'm told these are not defined.
So how to solve this problem?
Sorry for my poor English, hope you understand what I means.
Here are my functions and html file.
<html>
<head>
<meta charset="utf-8">
<title>Puzzle</title>
<script src="puzzle-localstorage.js"></script>
<script src="puzzle.js"></script></script>
</head>
<body onLoad="Init()" onkeydown="keydown()">
<p align="center">
<canvas id="board" height="600" width="600" style="border-style:double">
Your Browser doesn't support canvas
</canvas>
</p>
<p id="moves">Moves: <span id="movecount">0</span>
<input type="number" id="boardEdgeNum" value="3"/>
<input type="file" id="imgSrc"/>
</p>
function supportsLocalStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
function saveGameState() {
if (!supportsLocalStorage()) { return false; }
localStorage["puzzle.boardEdge"] = boardEdge;
localStorage["puzzle.blockPixel"] = blockPixel;
for (var i = 0; i < boardEdge; i++) {
for(var j=0;j<boardEdge;j++){
localStorage["puzzle.gameStatus."+i+j] = gameStatus[i][j];
}
}
localStorage["puzzle.image.src"]=imgElement.src;
localStorage["puzzle.move.count"] = moveCount.textContent;
if(gameInProgress)localStorage["puzzle.game.in.progress"] = "true";
else localStorage["puzzle.game.in.progress"]="false";
localStorage["puzzle.empty.block.X"] = emptyBlock.X;
localStorage["puzzle.empty.block.Y"] = emptyBlock.Y;
return true;
}
function resumeGame() {
if (!supportsLocalStorage()) {return false;}
if(!localStorage["puzzle.game.in.progress"]=="true"){return false;}
boardEdge=parseInt(localStorage["puzzle.boardEdge"]);
blockPixel=parseInt(localStorage["puzzle.blockPixel"]);
imgElement=new Image();
imgElement.src=localStorage["puzzle.image.src"];
gameStatus=new Array(boardEdge);
gameCompStatus=new Array(boardEdge);
for (var i = 0; i < boardEdge; i++) {
gameStatus[i]=new Array(boardEdge);
gameCompStatus[i]=new Array(boardEdge);
for(var j=0;j<boardEdge;j++){
gameStatus[i][j]=parseInt(localStorage["puzzle.gameStatus."+i+j]);
var x=(gameStatus[i][j]-1)%boardEdge;
var y=(gameStatus[i][j]-1-j)/boardEdge;
drawingContext.drawImage(imgElement,x*blockPixel,y*blockPixel,blockPixel,blockPixel
j*blockPixel,i*blockPixel,blockPixel,blockPixel);
drawLines();
}
}
gameStatus[boardEdge-1][boardEdge-1]=0;
gameCompStatus[boardEdge-1][boardEdge-1]=0;
moveCount.textContent=localStorage["puzzle.move.count"];
gameInProgress=(localStorage["puzzle.game.in.progress"] =="true");
emptyBlock=new Cell(parseInt(localStorage["puzzle.empty.block.X"]),parseInt(localStorage["puzzle.empty.block.Y"]));
return true;
}
<script src="puzzle.js"></script></script>
What is this? Is it typo? Or in your real code it is so too? Try to remove them. Javascript should see your functions. Where is declarations for Init and keydown functions? Does javascript see them?
Have you checked for any errors? I see one in the loop of resumeGame:
drawingContext.drawImage(imgElement,x*blockPixel,y*blockPixel,blockPixel,blockPixel
j*blockPixel,i*blockPixel,blockPixel,blockPixel);
should probably be:
drawingContext.drawImage(imgElement,x*blockPixel,y*blockPixel,blockPixel,blockPixel,
j*blockPixel,i*blockPixel,blockPixel,blockPixel);
Your url might be wrong. You are using a relative url instead of an absolute url, consequently the JS file must be in the same folder as the HTML Document.
Try an absolute url (e.g. http://www.servername.com/puzzle/js/puzzle.js") instead and check if that accomplishes anything.