Why Won't my JS Code Run? - javascript

For some reason I am getting this issue: Uncaught TypeError: Cannot read property 'value' of null on the document.getElementById line. What is the issue?? I have no clue.
HTML Code:
<html>
<head>
<title>I am a chrome extension</title>
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script src="scripts.js"></script>
</head>
<body bgcolor="#34495e">
<div class="login-card">
<h1>Please Enter Your Birthday</h1><br>
<form>
<input type="date" name="user" placeholder="Username">
<input type="submit" id="age" name="submit" class="login login-submit" value="Submit">
</form>
</div>
</body>
</html>
scripts.js
function getAge()
{
var age = document.getElementById("age").value;
console.log(age);
}
document.getElementById('age').onclick = getAge();

Using parentheses after a function invokes the function. To bind the event to the function simply reference getAge without parentheses, like this:
document.getElementById('age').onclick = getAge;
You should also be sure to wait until after the DOM is completely loaded using the onload event. You should also take time to carefully read properly bind javascript events.

Because you're including the script in the head, and it loads before the dom elements do.
You'll need to apply pswg's answer as well.
The way to fix this is simply use window.onload
window.onload = function () {
document.getElementById("age").onclick = getAge;
}

This is because you include you js file in the head, before your actual html gets evaluated. You cant getElementById because the element is not there yet!!
generally, js files are include at the bottom, right above the closing body tag. To make sure, use document.onload();

Related

How can I make a JavaScript function wait for input or value?

As you can see below, I have a function,createCharacter(), that calls another function, getUserInput(). This function is intended to grab the value of a text input element and return that value to be stored in the "name" variable within the createCharacter. However, if you run this code. It completely runs through both functions, never giving the opportunity for the user to input a value. Perhaps a more specific question is, how can I make this function wait for the variable to be defined before returning it to createCharacter? I've tried to wrap the code in a while loop that will run for as long as value is undefined. Didn't work, created an infinite loop and crashed. ANY solution to this problem will be greatly appreciated. I feel like the solution is so simple, but I just can't figure it out for the life of me. Thanks.
var messageDisplay = document.querySelector(".message-display");
var menuInput = document.querySelector(".menu-input");
var playerInput = document.querySelector(".player-text")
function createCharacter() {
messageDisplay.textContent = "Welcome! What is your name?";
var name = getUserInput();
messageDisplay.textContent = "Hello " + name + "!";
}
function getUserInput() {
var textValue = playerInput.value;
return textValue;
}
createCharacter();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<form class="menu-input-content">
<input class="player-text" type="text">
<input class="submit-button" type="submit">
</form>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I think you have a misunderstanding of how the DOM and the user interact. The DOM is event based. You can start by add an change event listener to your input element (or on the submit button):
menuInput.onchange = createCharacter;
And then remove the call to createCharacter, the last line in the code you posted.
This will then call the createCharacter() method when you change the text in the input at all, which is probably not what you want. You could also try:
var menuSubmit = document.querySelector(".submit-button");
menuSubmit.onclick = createCharacter;
And that is probably more on the right track.
However, given your misunderstanding in the first place, perhaps you need to reconsider how you approach your design?
The reason it runs through the code immediately is because of the last line. The browser loads the JS and executes everything in the global scope. Your query selectors are run and stored in those variables, the functions defined, and then on the last line you call one of the defined functions.
To fix this you need to redesign your app to be event based. Keep defining needed variables and functions in the global scope, as you are doing here, but then change your execution to be in response to events.
I think you are looking for something like this. You should be using the events to get what you wanted. You are executing createCharacter() before even the user clicked the Submit button. Hence you see "Hello !" as there is no user input initially.
function submitClicked(event) {
var messageDisplay = document.querySelector(".message-display");
var playerInput = document.querySelector(".player-text");
messageDisplay.innerHTML = "Hello " + playerInput.value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<input class="player-text" type="text">
<input class="submit-button" onclick="submitClicked()" type="submit">
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

How I build code such http://fiddle.jshell.net/bwKZt/152/ - HTML & Javascript

I need build code such : http://fiddle.jshell.net/bwKZt/152/
but my code dosen't work ! I am a beginner. Please help me.
index.php:
<!DOCTYPE html><html>
<head>
<script>
$("#label").bind("keyup", changed).bind("change", changed);
function changed() {
$("#url").val(this.value);
}
</script>
</head>
<body>
<input type="text" id="label" />
<input type="text" id="url" readonly />
</body>
</html>
Some of the JavaScript here isn't native JavaScript , but is using a plugin called jQuery that makes searching and manipulating HTML elements easier.
When you see $(), that's the jQuery way of finding elements. But it won't work because you don't have jQuery referenced at all.
If you don't want to use jQuery, you can find elements with something like document.getElementById('label').
But lots of people use jQuery to make referencing page elements short and sweet, as with $('#label').
Try to reference jQuery first, like:
<!DOCTYPE html><html>
<head>
<!-- The below line references an externally hosted copy of jQuery 2.2.4 -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// The below chunk is telling it to bind to the keyup event only AFTER the document has fully loaded.
// Sometimes when your binding code is executed, the elements you wish to bind to aren't loaded yet.
$(document).ready(function(){
$("#label").bind("keyup", changed).bind("change", changed);
});
function changed() {
$("#url").val(this.value);
}
</script>
</head>
<body>
<input type="text" id="label" />
<input type="text" id="url" readonly />
</body>
</html>
The first problem is because you haven't include jquery with a script tag to solve that add this code in the head of you html file if you have the Internet connection to load Jquery from CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
or you can download Jquery file from Jquery site and you will have it locally
after that you must execute this code after the executing the jquery ready function
$(document).ready(function(){
$("#label").bind("keyup", changed).bind("change", changed);
function changed() {
$("#url").val(this.value);
}
})

How to send parameters in javascript function used in HTA

I am trying to pass filepath value to publish.bat.
Can some one please help me parameterize below JavaScript.
<html>
<head>
<HTA:Application id="AppExecute"
ApplicationName="AppExecute"
WindowState="maximize">
<script language="JavaScript"><!--
function myapp(filepath){
var cmd = new ActiveXObject("WScript.Shell");
cmd.run("cmd /K CD C:\\publish & publish.bat C:\\publish\\prop\\lvl.Prop "&filepath)
}
--></script>
</head>
<body>
<font color=Blue><font size=3>Test Publisher
<br>
<Input type="text" name="filepath" title = "Do not change name of property files e.g. l2.ese">
<input type="button" value="CMD" onclick="myapp(filepath)"><br>
</form></center>
</body>
</html>
I am getting Error:
Script Error
Your code has several mistakes...
#Teemu explained some of them in the comment.
Then your buttons aren't properly enclosed within a form element. As I can see, there is only an ending tag for the form element.
After correcting that, you should change onclick event to:
onclick="myapp(this.form.filepath.value)"

Working with external JavaScript functions and HTML

Thank you in advance for helping me with my issue. I was wondering if someone could explain this for me as i am self teaching about JavaScript JQuery. What i am trying to do is push a message into a variable that is in the parameters of a function. Then i want to display the message using the function by calling it back to the html file that i originally had. So i want write a message in my function and print to my html page. I think i maybe in the right direction here is my source code. I am trying to get use to write with external javascript files as i think it is much cleaner way of working with HTML, CSS3, and JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src=".js"></script>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<form>
<input type="button" value="Click me" id="message "onclick="test();" />
</form>
</body>
</html>
External JavaScript file.
function test(message){
alert("Hello");
}
Use this.value to get the value of the input
<input type="button" value="Click me" id="message" onclick="test(this.value);" />
And then use the message you get
function test(message){
alert(message);
}
To show this message on your page, create an element on the page
<div id="message"></div>
Then, in your test function, instead of alert, set the innerText or innerHTML to the message
document.getElementById('message').innerText = message;
To show message in popup do it this way
Html:
<input type="button" value="Show message in popup" id="message "onclick="test2('hii this is my message');" />
JS:
function test2(message)
{
alert(message);
}
To show message in div
Html:
<input type="button" value="Show message in div" id="message "onclick="test('hii this is my message');" />
<div id="message"> </div>
JS
function test(message)
{
document.getElementById("message").innerHTML = message;
}
Demo : Fiddle
Adding the message: The easy way to do this would be by using jQuery or a javascript library of your choice. Otherwise, you can simply do this:
Create an empty div to display the msg with an id="msg"
and in your javascript function:
document.getElementById("msg").innerHTML = "Your message";
jQuery is much more fun: you can use readily available functions like .html() and .append()
You definitely want to do this, as it is much MUCH cleaner to do so. It also lets you use the same code in multiple places.
Look at this: http://www.w3schools.com/js/js_whereto.asp
(down by 'external JavaScript')
Essentially, you need to save the .js file as an actual file, like filename.js:
<script type="text/javascript" src="filewithcode.js"></script>
where filewithcode.js is the file path to the JavaScript file you have created.
Hope this helps

I get an undefined error in my error console

My myclickHandler function works perfectly but when I go on to my error console I get this error:
document.getElementsByName("prequestion")[0] is undefined;
Below is my code
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
if(validation()){
openSessionPopup();
}
</script>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>10: </strong><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="myClickHandler()"/></p>
</form>
</body>
My question is what do I need to remove this error? because my function works does it matter if it shows an error in the error console?
Chances are you're loading the javascript before the DOM (or even possibly the HTML) has loaded properly.
For example, the following reproduces the same error as described in your question :
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
}
</script>
<input type="" name="prequestion" />
Whereas the following does not. The error is not present and the code works fine.
<input type="" name="prequestion" />
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
}
</script>
Trying to attach the event listener to an element which doesn't technically exist yet causes problems. You can check for the browser reporting the page has been loaded before attaching the event if needs be but be aware that browsers report this in different ways. Librarys such as jQuery provide useful means to test this such as $(document).ready(function(){});
Edit: I've just seen that you've added the relevant HTML too. It appears that this is in fact the case and the reason you're still seeing the expected behavior is because you're also using the onclick="" attribute on the input element. This is where the function is being called on click, and the event handler isn't being attached as you expect.
Edit #2: You also appear to be missing a closing } for your function. And I've now tested with your exact HTML and moving the script to just above the body tag resolves the error and correctly attaches the function to the click event.
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>10: </strong><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" /></p>
</form>
<script type="text/javascript">
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
function myClickHandler(){
alert('test');
} // This was missing
</script>
</body>
I suspect that the problem is that there are no elements with the name attribute set to "prequestion".
If you're getting that error, then your script doesn't actually work, so you should fix it.

Categories