In my palindrome checker, i can't obtain value from the HTML input text-field. I tried various methods including query-selectors. But nonetheless is working. Error in the validator is document.getElement(...) is null.
i need to find whats wrong with my code. Is there any problem in my DOM?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i = document.getElementById('boiler').value;
function check_pal() {
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
I am little sure that my problem is with document model. Because i get correct result when i directly assign the value to the variable. Or else i get "undefined is not a palindrome"
Update your script to following
<script>
function check_pal() {
// move this line inside the function
var i = document.getElementById('boiler').value;
// rev(); // Also removed this un-necessary call
if (i == rev(i)) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
// modify function to take input as argument rather than relying on global variable
function rev(i) {
i = i + "";
return i.split("").reverse().join("");
}
</script>
Reasoning - When you manually assigned the value of i, then it was running correctly. However, when were trying to read it from the getElementById, the element did not existed by then and it throws a JS error (cannot read property 'value' of null), hence, the error (as i was never initialized and remains undefined). Move the retrieving of value inside the function where the latest value can be retrieved and stored in i.
This should solve it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" href="ex.css" type="text/css">
<!--<script src="ex.js"></script>-->
<script>
var i;
function check_pal() {
i = document.getElementById('boiler').value;
rev();
if (i == rev()) {
alert(i + " is a palindrome");
} else {
alert(i + " is not a palindrome")
}
}
function rev() {
i = i + "";
return i.split("").reverse().join("");
}
</script>
</head>
<body>
<div>
<h1>Palindrome Checker</h1>
<p>- Word limit "18000"</p>
</div>
<div>
<input type="text" id="boiler" name="boiler" /><br>
<input type="submit" name="palcheck" id="butn" value="Is it a Palindrome?" onclick="check_pal()" />
</div>
</body>
</html>
Now the i variable gets assigned in the check_pal function and declared in the global space so both functions can access it. I think you should take a close look in scope in javascript.
Related
i created an array and insert elements by array.push(). when i console.log(array) it gives me following out put output of console.log(array)
when i console.log(array[0]) it gives me undefined. why is happing and a blue i tag appear in picture which says "this value was evaluated on first expanding it may have changed since then in array javascript" what does means. please help me to understand the problem
here the full code
index.html =>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>zip reader</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<body>
<h3>Choose the local(s) zip file(s)</h3>
<input type="file" id="file" name="file" multiple /><br />
<div id="result_block" class="hidden">
<h3>Content :</h3>
<div id="result">
</div>
</div>
</body>
<script src="jszip.min.js"></script>
<script src="jszip-utils.min.js"></script>
<script src="app1.js"></script>
<script src="FileSaver.min.js"></script>
</html>
app1.js =>
var array = []
var contents = []
var $result = $("#result");
$("#file").on("change", function(evt) {
// remove content
$result.html("");
// be sure to show the results
$("#result_block").removeClass("hidden").addClass("show");
// Closure to capture the file information.
function handleFile(f) {
var $title = $("<h4>", {
text : f.name
});
var $fileContent = $("<ul>");
$result.append($title);
$result.append($fileContent);
var dateBefore = new Date();
JSZip.loadAsync(f) // 1) read the Blob
.then(function(zip) {
var dateAfter = new Date();
$title.append($("<span>", {
"class": "small",
text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
}));
zip.forEach( function (relativePath, zipEntry) {
var y = zipEntry.name
array.push(y);
$fileContent.append($("<li>", {
text : zipEntry.name
}));
});
}, function (e) {
$result.append($("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + f.name + ": " + e.message
}));
});
}
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
handleFile(files[i]);
}
console.log(array[0])
});
When you console.log an object (including arrays), it isn't being serialized, and only a reference is passed to a console. When you expand it, this reference is used to check the state of this object.
Most probably what's happening is the following sequence:
console.log(array) // passes array reference to a console
console.log(array[0]) // prints undefined immediately
array.push(...) // an actual array modification
you expand the object, and console checks the content of an array
PS.
It's reasonable to ask, what will happen, if the reference will become invalid due to any reason.
For browsers - it's simpler, since the console and JS program run under same parent process, browser is responsible for everything.
But if you'll ever try to debug Node process, which has the same API of passing the reference, you will face strange issues all over around, like this one: No debug adapter, can not send 'variables VSCODE
guys!
I'm giving my firsts steps in JS and in OOP in general, and I am trying to build code perhaps too stilized for my level, but I would like my sets and gets to be like "object.a" and "object.a = value" and not call them "getA" and "setA" and, above all, definitively not like a function ("object.a()" and "object.a(value)").
I design this page to find my way of doing but it is driving me crazy:
I don't know why "wa" keeps on incrementing it's value till it flips out with the message "too much recursion".
I don't see how to do for get a and set a to see "a" inside of "coso".
Can anybody help me?
Here's my code:
<!doctype html>
<html>
<head>
<link href="/style.css" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<style>
</style>
<script>
function coso() {
var a = 1024;
coso.prototype = {
get a() {return this.a},
set a(valor) {this.a = valor}
}
this.muestraA = function() {if(a === this.a) {alert("¡Yupi!")} else alert("A vale: " + a +", pero a vale: " + this.a)}
}
function GuardaA(valor) {
var obj = new coso();
obj.a = valor;
obj.muestraA();
return obj.a;
}
</script>
<title>Prueba Objeto</title>
</head>
<body>
<h1>Prueba Objeto</h1>
<form onchange="x.value=GuardaA(wa.value)">
<label for="wa">Valor para A</label>
<input type="number" id="wa">
<label for="x">A vale:</label>
<output id="x" for="wa"></output>
</form>
<footer></footer>
</body>
</html>
You're getting infinite recursion because the get a() function tries to read this.a. But this is the object that has the get a() function, so it calls that function again, and so on repeatedly.
You should be accessing the local variable a, because the whole point of defining a getter and setter is because you want to use that variable instead of a regular property.
function coso() {
var a = 1024;
coso.prototype = {
get a() {return a;},
set a(valor) {a = valor;}
}
this.muestraA = function() {
if(a === this.a) {
alert("¡Yupi!");
} else {
alert("A vale: " + a +", pero a vale: " + this.a);
}
}
}
So here is the problem.I want user to enter number of index in text box for array. After taking index i want user to enter value from a prompt box to store in that array but that prompt box is coming over and over again and i have to click on button every time to take input
Here is the code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">
<h1 id="demo"></h1>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Java Script:
var data = document.getElementById("t1").value;
function record(){
var crap = new Array(data);
for(var i=0;i<crap.length;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
In your case, you are retrieving data outside the function. Thus its value will be 'undefined' and the crap will became the array of one value that is undefined. So crap.length will be always 1.
Try this:
function record(){
var data = document.getElementById("t1").value;
var crap = []
if(crap != undefined)
for(var i=0;i<data;i++){
var tmp = prompt("Add something in my array","");
crap.push(tmp);
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
}
Enjoy coding ....
Try this,This will solve your issue.
You are just declaring an array named crap, and you are trying to get the crap.length even before the array is filled, so you are getting the issue. Since data has your value try looping with data value.
function record(){
data = document.getElementById("t1").value;
var crap = new Array(parseInt(data)); // you should take data here, since crap is empty at this point.
console.log(data)
for(var i=0;i<data;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">
<h1 id="demo"></h1>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Please run the code snippet and check the answer.
I am new to Javascript.
I am making my first Adventure Game.
I tested the following code out with an onClick and it worked fine:
// JavaScript Document
function changeColour()
{
if (document.getElementById('colourTest').style.backgroundColor='yellow')
{
document.getElementById('colourTest').style.backgroundColor='red';
}
else
{
document.getElementByID('colourTest').style.backgroundColor='yellow';
}
}
var direction;
direction = prompt("Which direction would you like to go ?");
if ( direction == "North" )
{
changeColour();
}
else
{
console.log("You can't go in that direction ?");
}
This is the HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script language="javascript" type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body>
<div id="colourTest">
</div>
</body>
</html>
I want the Yellow div to turn red when the user enters the word North, otherwise, the user is told that they can't go in that direction.
I am sure that this is some kind of syntax error :D
Hi, Here is an update:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<script type="text/javascript" ></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body onload="load();">
<img id="myimg" alt="My Image" src="images/image1.jpg" />
<form>
<input name="heading" type="text" id="which" value="" />
</form>
</body>
</html>
Here is JS:
// JavaScript Document
var img = new Image();
img.src = "images/image1.jpg";
function whichImage(b)
{
var image = document.getElementById("myimg");
if (b == "North")
{
image.src = "images/image2.jpg";
}
else
{
image.src = "images/image1.jpg";
}
}
function whichDirection (x)
{
if (x == "North" || x == "South" || x == "East" || x == "West" )
{
document.write("You choose to go " + direction);
}
else
{
document.write("You can't go in that direction");
}
}
function load()
{
var direction = document.getElementById('which').value;
whichDirection(direction);
whichImage(direction);
}
I don't understand why the input direction from the user isn't allowing the image to change to image2.jpg, when the word, North is input by the user.
Can JS actually capture text input from html and then use this with variables in functions?
More over, with this version, the DOM doesn't seem to have loaded, as there is no image to be seen.
The two errors I see right away (there may be more) are...
if (document.getElementById('colourTest').style.backgroundColor='yellow')
You're assigning instead of comparing. Use == for comparison (as you do elsewhere). And...
document.getElementByID('colourTest').style.backgroundColor='yellow';
JavaScript is case-sensitive. The function name should be getElementById (as you do elsewhere).
In this case there was a logical error and a syntax error. The latter can often be noticed by looking at the JavaScript console in your browser's debugging tools. If it tried to execute that line of code, you'd see an error there. Logical errors, on the other hand, can be trickier to pinpoint. For those you'll want to familiarize yourself with the debugger in your browser's debugging tools.
You can click on a specific line of JavaScript code to set a "breakpoint" where the execution of code will pause. Once paused, you can examine the runtime values of your variables, step through the execution line-by-line to check its behavior, etc. This is how you validate that the code is doing what you expect it to do.
I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>