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.
Related
I know this question may be stupid, but I'm new to JQuery and failed to guess (even after hard search at Google) Why My Function failed to Show me Alert on Click Event of Button, (I'm trying to do more tasks but for debugging purpose I'm showing alert).
<!DOCTYPE html>
<html>
<head>
<title>WebSite Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
$(document).ready(function(){
$('#foo').click(function(){
alert('ggg');
});
});
</script>
</head>
<body>
<input type="button" name="" value="Get Data" id="foo">
</body>
</html>
As #Pranav mentioned, you should separate the scripts, so each can work.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#foo').click(function() {
alert('ggg');
});
});
</script>
I'm Totally Agreed with Answers of above two users, You have to Put Your Code away from the tags referencing the Libraries, What you need to do is place your logical code may be of Javascript or JQuery in Another Script Tags
This is a basic question of javascript.
I'm doing my personal webpage. When people click the button ("botón") this message should appear: "clicked!"
My html5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
<link href="website.css" rel="stylesheet"/>
<script src="script.js"></script>
</head>
This is the specific part of the button:
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button>botón</button>
My javascript code: (stored in the file: "script.js")
$("button").on("click", function() {
alert("clicked!")
});
But i click and no message appear (Chrome or Firefox).
UPDATE 1:
Apparently, i was following a Jquery tutorial.
I need to do that in basic javascript. What should i do. Code examples are welcome.
UPDATE 2: Based on suggestions, my code still does not work.
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
My new script:
document.getElementById('myButton').addEventListener('click', function(){
alert('clicked');
}), false);
document.getElementById('myButton').addEventListener('click',function(){
alert('Clicked!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
</head>
<body>
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
</body>
</html>
Make sure to place your script right in front of the closing </body> tag, the elements can't be found if the DOM isn't loaded at the time your script gets loaded:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>omargonzalesdiaz.com</title>
<link href="website.css" rel="stylesheet"/>
</head>
<body>
<input type="email" placeholder="Your email">
<input type="submit" placeholder="Send">
<button id="myButton">botón</button>
<script src="script.js"></script>
</body>
</html>
script.js
document.getElementById('myButton').addEventListener('click',function(){
alert('Clicked!');
});
You should add an id to your button, then:
document.querySelector("#mybutton").addEventListener("click",function(){
alert("BUTTON CLICKED");
});
Where mybutton is your button ID. Try to work with IDs so your DOM query isn't getting more than one element.
Example:
http://jsfiddle.net/fthupjpd/
EDIT: Don't use jQuery for that :)
You dont have the jquery lib in your html, but you are using $, which is part of jquery (it's the facade for the api/lib)
add:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
before you cann you click code. You need to also make sure the dom has loaded when you call you event handler, try:
$(function () {
$("button").on("click", function() {
alert("clicked!")
});
});
IF you dont want to use jQuery, give your button an id
<button id="myButton">botón</button>
then in your code
document.getElementById('myButton').addEventListener('click', function(){
alert('clicked');
}), false);
Here are the docs on native event handlers
document.getElementById('myButton').onclick=function(){
alert('clicked');
};
For a good start with JavaScript, I find W3schools very good:
http://www.w3schools.com/js/default.asp
EDIT
see Michael's answer for where to place your scripts when you need them to access the document elements. The body needs to be loaded before you can reference them on your JS code.
You have two problems.
You haven't defined $. It looks like you are trying to use the jQuery library. You need to include that in your page before the script.
You are trying to bind an event handler to all the button elements in the document while the head section is being parsed. At that point, there is no button elements. You need to move the script element to after the button elements (or use a ready or load event hander).
The code does not run as written. If the button click part (the 3 lines after the first alert) is removed it works fine. It seems like any edits made to the JS/JQ area lead to issues. What could be going wrong here?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Problem #2</title>
<link rel="stylesheet" href="css/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Problem #2:</h1>
<form>
<input type="number" placeholder="Enter your cents" min="0" />
<input type="button" name="Solve" value="Solve" />
</form>
<div id="answer">
<div id="quarters"></div>
<div id="dimes"></div>
<div id="nickels"></div>
<div id="pennies"></div>
</div>
<script src="js/jquery-2.0.3.min.js"></script>
<script>
$( document ).ready(function() {
alert("Handler for .ready() called.");
$('button').click(function{
alert("Hello World");
});
});
</script>
</body>
</html>
This has a syntax error:
$('button').click(function{
alert("Hello World");
});
and needs to be this (missing parens):
$('button').click(function () {
alert("Hello World");
});
In the future, you should look at the debug console and it will tell you what line your syntax errors are on and often give you an idea what the error is. You can also run your code through jsHint (just paste in the relevant code) and it will often give you details on where syntax is wrong or suspect.
In addition, since you don't have any <button> tags in your HTML, your selector is also probably wrong. If you're targeting the solve button, then you should probably change your HTML like this:
<input id="solve" type="button" name="Solve" value="Solve" />
and your HTML like this:
$('#solve').click(function () {
alert("Hello World");
});
You are missing the parenthesis after function in the third line of your script.
Also, as #ArtOfCode in the comments said, your selector should be input[type=button].
It should look like this:
$('input[type=button]').click(function () {
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();
I have the following (simplified) code:
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" />
<script language="javascript" type="text/javascript">
function testFunction() {
alert('It works');
}
</script>
</head>
<body>
<form method="post" action="test.html" onsubmit="testFunction()">
<input type="submit" value="Test" />
</form>
</body>
</html>
My testFunction() function works fine by it self, that is until I import jQuery with the line
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" />
Now it fails and tells me that
Uncaught ReferenceError: testFunction is not defined
I am hoping this is a newbie mistake and that I am missing something obvious. Notice that I haven't even try to use jQuery yet.
You need to close the <script> tag fully.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
Works great on jsfiddle after changing:
http://jsfiddle.net/PVYM9/
Also, in HTML5 you can shorten the doctype to just <!DOCTYPE html>, and you don't need to define type properties for your <script> tags. See jsfiddle for example.
You have to close the script tag in the right way
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
(note the closing </script> tag)
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> // close the script tag properly
<script type="text/javascript"> // there is no need of writing language="javascript"
function testFunction() {
alert('It works');
}
</script>
hey man there is no need of writing language="javascript" because type already specifies it!
Despite being valid XML, many HTML elements (such as script, textarea etc) don't work well in most browsers if you close them using a trailing slash (i.e. <element />). You need to create open and close tags for them to work (<element></element>). That seems to be true for XHTML as well.
Others, like your input tag, work fine the way it is. I don't know why some require a closing tag and others not, neither a list of those elements, I just know some of them from experience...