Javascript code works from console but not file [duplicate] - javascript

This question already has answers here:
javascript code not work in HEAD tag
(5 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
I was recently introduced to Web Storage on my current course and have been tasked with taking input from a text field (input) using a button, then creating a key and value for this text field data. It seemed rather trivial. I produced some code in attempt to get it working. However the code did not work as expected.
Here is the (non-working) code I managed to produce:
HTML:
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="app.js" charset="utf-8"></script>
<meta charset="utf-8">
</head>
<body>
<p>Forename:</p>
<input type="text" id="FName"><br>
<button type="button" id="Submit">Submit</button>
</body>
</html>
JS:
var SubmitButton = document.getElementById('Submit');
var TextField = document.getElementById('FName');
SubmitButton.addEventListener('click', function(e){
ToTextField();
});
function ToTextField(){
var input = document.getElementById("FName").value;
localStorage.setItem("Text", input);
}
Though this code does not work, I have analyzed the developer tools tab in my browser (Firefox), and noticed that I get the following error:
TypeError: SubmitButton is null [Learn More] app.js:6:1
If I then enter the following lines of JS into the Console (which are the same in my file), the submit button seems to work as I expected it. I can't figure out the problem:
var SubmitButton = document.getElementById('Submit');
SubmitButton.addEventListener('click', function(e){
ToTextField();
});
Can anyone spot the problem I am having here?
Thanks :)

Related

Unable to run a script within popup.html in a Chrome Extension [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Returning Chrome storage API value without function
(6 answers)
Closed 1 year ago.
I'm learning how to make Chrome extensions, and I'm having problems attaching a script to the popup.html.
The foreground.js stores some words which I'm calling labels in the local storage using chrome.storage.local.set(). What I want the popup page to do is simply show these labels.
I know the labels are getting stored, as I've debugged that process and it works fine.
The popup.js code:
function displayLabels(){
var labels = [];
chrome.storage.local.get("labels",value=>{
labels=value.labels
});
console.log(labels)
var mainDiv = document.getElementById("mainDiv")
for(var i=0;i<labels.length;i++){
var mainDiv = document.getElementById("mainDiv")
var textBox = document.createElement("h5")
textBox.innerText = `Label${i}: ${labels[i]}`
mainDiv.appendChild(textBox)
}
}
document.onload=(event)=>{
displayLabels()
}
//window.onload=(event)=>{
// displayLabels()
//}
And the popup.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div id="mainDiv">
</div>
</body>
</html>
I have checked the spelling of the key labels while storing it, it is correct. I have also set the storage permission in the manifest.json
The displayLabels() function does not get called. I tried a simple console.log("hello") in the first line of displayLabels() too, but that also did not work.

Why wont JQuery hide/show elements on my web page and how do I fix it? [duplicate]

This question already has answers here:
Is $(document).ready necessary?
(5 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I'm having a problem that has just now started happening for no reason. I'm playing around with a block that detects whether you are using Adblock. It sets a variable, var canRunAds = true; in a file titled ads.js which is not really ads but all adblockers will block it regardless. Next, somewhere in index.html tests to see if canRunAds is defined or not like this:
<DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="../javascript/ads.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
if( window.canRunAds === undefined ){
$("#adblock_off").hide();
$(".adblock_off").hide();
console.debug("adblock enabled");
}
else {
$("#adblock_on").hide();
$(".adblock_on").hide();
console.debug("adblock disabled/nonexistant");
}
</script>
<div>
<img src="../images/adblock_off.png" id="adblock_off"></img>
<img src="../images/adblock_on.png" id="adblock_on"></img>
<p class="adblock_off">Thanks for disabling your adblock!</p>
<p class="adblock_on">Disable your adblock, no ads here!<p>
</div>
</body>
This has always worked for me, however it has stopped working. The script runs the console.debug and it shows up in the console, but the elements wont hide. Any explaination?
PS: This is all documented at this GitHub repo

getElementById() work in html file but not in js file [duplicate]

This question already has answers here:
Javascript can't find element by id? [duplicate]
(5 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
i cannot find answer to my question in someone else post so here it is:
getElementById return null in java script file (also while testing in console) but work in html file
HTML file
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/app.js"></script>
</head>
<body>
<p id="stuff">Some text</p>
</body>
</html>
JS file
var title = document.getElementById('stuff');
console.log(title);
title.style.color = "#D4F34A";
You can add a callback function for the document event DOMContentLoaded event like so, and inside that function do your desired code:
//Add this into your script file, and anything you want to have execute once the document
//is fully loaded go inside of the function
document.addEventListener("DOMContentLoaded", function(event) {
var title = document.getElementById('stuff');
console.log(title);
title.style.color = "#D4F34A";
});

Script only works in console [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I recently started to learn jQuery so I had some exercices to do. This one is about displaying messages by clicking on page element. Here is the code :
var $caption = $('caption');
$caption.on('click', function(event) {
    $(' <td>Wp it worked</td>').insertAfter('tr');
});
<!DOCTYPE html>
    <html>
        <head>
            <title>Happy Birthday !</title>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
            <script type="text/javascript" src="js/script.js"></script>
            <link rel="stylesheet" type="text/css" href="css/style.css">
            <meta charset="utf-8">
        </head>
        <body>
                <table>
                    <caption>Click here</caption>
                        <tr>
 
                        </tr>
                </table>
        </body>
    </html>
So the problem is that it doesn't work. When I write the script in the console it works perfectly, but with the js file it basicly doesn't. So I know it's not a problem of folder because when I put something like alert('test'); in the js file it works. Someone knows why ?
it is working in the snippet , however you may try this.
$(document).ready(function () {
var $caption = $('caption');
$caption.on('click', function (event) {
$(' <td>Wp it worked</td>').insertAfter('tr');
});
});

How to run a JavaScript function on an input field when a button is pressed [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 6 years ago.
I'm trying to remember how to associate HTML and JS through different actions, so I just wrote a simple reverse script (any number would be turned into a string and reversed)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Number Reverser</h1>
<script>
function Reverser(n){
n = n + "";
return n.split("").reverse().join("");
}
function ExecuteRev(){
console.log(Reverser());
}
</script>
<input id="bubu">
<button onclick="ExecuteRev()">REVERSE 'EM</button>
</body>
</html>
The ridiculous part is that the console returned
denifednu
My genius JS level managed to reverse the error itself.
How I can connect the input to the function to be executed on the button press and displayed in a div (any div, not console)?
I'm not entirely sure what you mean but I think you might be talking about using the DOM. For instance, to update a div with id="x", do the following.
document.getElementById("x").innerHTML = "New content";

Categories

Resources