I am trying to verify if my checkbox is checked. I have looked up many solutions, and they all point to this :
html :
<body>
<input type="checkbox" id="terms" name="terms" />
<label for="terms">Agree with terms</label>
javascript :
let checkbox = document.querySelector("#terms");
console.log(checkbox.checked);
But the console is returning :
"Uncaught TypeError: Cannot read properties of null (reading 'checked')"
There is no other code interfering with this as I stripped it down to this small example to see if my project was interfering with the functionality, but even with the most basic code '.checked' is returning an error. Has there been an update to this feature?
<input type="checkbox" id="terms" name="terms" />
<label for="terms">Agree with terms</label>
<script>
let checkbox = document.querySelector("#terms");
checkbox.addEventListener('change', () => {
console.log(checkbox.checked);
})
</script>
or
let checkbox = document.querySelector("#terms");
console.log(checkbox.checked);
I figured out the issue, I was not including 'defer' in my script.js link. Its all fixed thank you!
You will run into unexpected issues if you use defer.
Instead, use the DOMContentLoaded event to trigger your script.
Using defer allows that script to be executed after the DOM is done being parsed, but before the DOM content is loaded.
It’s likely that you’re deferred script will run too soon and crash when you try to access an element that doesn’t exist yet.
You can link your script in the <head> as long as you have it run when that event fires off.
document.addEventListener('DOMContentLoaded', function () {
let checkbox = document.querySelector("#terms");
checkbox.addEventListener('change', () => {
console.log(checkbox.checked);
})
})
EDIT: To answer the question from your comment above, linking to the JavaScript file in the head means that it will run before the html is built.
Putting the code in a script tag in the html means that it won’t be executed until DOMContentLoaded has triggered.
That happens after the link using defer and after the script is executed from the head.
Wrap your code up to only execute on DOMContentLoaded and you’ll avoid a lot of headaches in the future 😎
Related
I am a cybersecurity student trying to understand some basic HTML injections. I have been working on this code for a few days and can't understand what I am doing wrong. The code that I have currently does allow for injection, for example if I put <h1>test</h1> into the textbox, it will display test as a header. But if I try <script>alert(1)</script> it won't actually run the script. I have tried setting the value of the text box to "" or with the thought that I could close out that line by inputting the following into the textbox: "><script>alert(1)</script>
I've also tried to cancel out the remainder of the code by adding a comment to the end like this: <script>alert(1)</script><!--
I've tried a number of combinations of each with no luck. Now I actually need to be able to inject a script since I'm playing around with CSP and how that affects injection of scripts into the webpage. I currently DO NOT have a csp specified that would restrict the JavaScript from running. Some other things I've tried include using different browsers, changing browser security, and ensuring that JavaScript is enabled in the browser. Any help would be greatly appreciated!!
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
That's because <script>s run at page load, and, when the label's content change, the scripts have ran already.
However, if you inject <script> tags to a different page (through the backend (XSS means Cross-Site Scripting)), it does work.
Alternatively, to make it work in a scenario, where the content injected after page load (like your case), you can use JS events (like onclick) to run your code:
<div onclick="alert(1)">Click me!</div>
Or, to execute it without user interaction, you could use an <iframe>'s onload event:
<iframe onload="alert(1)" style="display:none"></iframe>
to execute javascript from your form, you can try:
<iframe src=javascript:alert(1)>
or
<img src=x onerror=alert(1)>
Also worth noting:
script elements inserted using innerHTML do not execute when they
are inserted.
To manually execute JavaScript, you may do the following
without editing your HTML file, add this to the Input field on your Browser.
<iframe onload="alert(1)" style="display:none"></iframe>
More information on why this works here
More on how you can perform actions like this here: developer.mozilla.org
<html>
<script language='JavaScript'>
function getwords(){
textbox = document.getElementById('words');
label = document.getElementById('label');
label.innerHTML = textbox.value;
}
</script>
<body>
<input type="text" id="words">
<input type="button" onclick="getwords()" id="Button" value="Enter" />
<label id="label">
</label>
</body>
</html>
I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});
There is an html as follows:
<input id="currency_factor" type="text" style="display:none;" value="20"/>
And there is a jquery function:
$(document).ready(function(){
var currency_factor = $('#currency_factor').val()
alert(currency_factor);
}
Upon refresh the html line shows on the browser as:
<input id="currency_factor" type="text" style="display:none;" value="0"/>
But jquery returns 20.
Why is this happening?
Try adding this to the header of your html file to disable caching:
<meta http-equiv="Cache-Control" content="no-store" />
There are actually a number of cache control tags that may or may not be needed, depending on the browsers being used. Here's another posting on StackOverflow that lists some of them: Using <meta> tags to turn off caching in all browsers?
Try by first initializing it and then setting it
$(document).ready(function(){
var currency_factor = 0;
currency_factor = $('#currency_factor').val()
alert(currency_factor);
}
Do you perhaps have more than one element with an id of currency_factor. The first one's value will probably be returned.
Another possibility is that the value is changed after the $(document).ready() function has executed. Try running $('#currency_factor').val() in the browser console after load. If it returns 0 then it was changed after the page load.
I need an image click to execute a js function. I have it working in my project, but I have other code to develop so I'm trying to use jsfiddle. But I can't get this simple code to work in jsfiddle. when I use jsfiddle and I click the image, nothing happens.
What am I missing in my efforts to use jsfiddle?
My HTML
<div>
<img id="additem" Title="Add Item" onclick="myfunc()" OnMouseOver="this.style.cursor='pointer';" OnMouseOut="this.style.cursor='default';" src="~/images/Sign_Add_Icon_32.png" />
</div>
My JS
function myfunc() {
alert("hello");
}
Remove onload in framework and extensions, set it to in head or in body.
DEMO
This works! But what was the problem?
You can't wait for the document to load in that case, because myfunc isn't defined before the Javascript is executed after the HTML loads.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
In the code at the line marked as //Error in comments. I get Javascript error saying: "Cannot read property style of 'null'". I have no idea what it is not able to find the object. I have thought and tried everything. Please help. Here is the code:
<script type="text/javascript">
$.getJSON('https://graph.facebook.com/647045111?fields=first_name&<%= Session["Token"] %>',
function (data) {
$('#userName').html(data.first_name);
});
document.getElementById('connectedUnregistered').style.display = 'block'; //Error
</script>
<div id="userName"></div>
<div id="disconnected" style="display:block;">
<div id="heading">Facebook login</div>
<div id="fbConnectButton"><img src="/Content/Images/fbconnect.png"/></div>
</div>
<div id="connectedUnregistered" style="display:none">
<div id="heading">Register Now</div>
</div>
You are executing your javascript code BEFORE the <div id="connectedUnregistered" /> was actually created.
Also note that you did not close your <div> with a corresponding </div>.
So move your javascript code to a part below your HTML. Or execute it after the page finished loading. If you are using JQuery you can do:
<script>
$(document).ready(function() {
... your code ...
});
</script>
Put your script at the end of the HTML document instead of the beginning, and see if that solves things.
JavaScript can't edit the DOM element because it hasn't been created yet.
Perhaps try placing this code in a
$(document).ready(function(){
//Code
});
block
in my case it was because of having this line at the beginning of the jsp/html(whatever) file:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
removing it solved the problem for me(I do not remember what it was doing on my page at first place)
Also, if in some part of the code you are using document.write it's very common to get null.
The script is trying to get the element before the element is loaded. Place the script after the element or put it in a load or ready event.
The code executes prior to the element being created. Since you are using jquery, simply wrap it in document.ready:
$(function(){
// code goes here
});
This will execute after the DOM is created.
The javascript code is running before the DOM is fully available and the call fails. Try the following instead
$(document).ready(function() {
document.getElementById('connectedUnregistered').style.display = 'block'; //Error
}
This error could also indicate that the element doesn't have an ID.
<input type="text" name="myelem" />
Make sure your element has an ID.
<input type="text" name="myelem" id="myelem" />