Button in JavaScript is not working as expected - javascript

An error message appeared after adding my button which calls a function in JavaScript. I cannot find the problem.
Sorry for the faults. I am French and I'm using Google Translate.
Here is the part of the code in question:
document.getElementById("jouer").onclick = start();
document.getElementById("jouer").onclick = function () { alert('defis[0]'); };
<input id= "jouer " type="button" value="jouer" click="start()"/>;
And the error message is:
Uncaught SyntaxError: Unexpected token '<'

It seems like you are trying to run both JS and HTML in one file.
To get it to work, you need to create a separate file with HTML stuff and use
<script src="your-js-file.js"></script> in the HTML file for the browser to be able to run JS.

function start() {
alert('i am working')
};
document.getElementById('jouer2').onclick = start
<input id= "jouer " type="button" value="jouer" onclick="start()"/>;
<input id= "jouer2" type="button" value="jouer2"/>;
target.onclick = functionRef;
functionRef is a function name or a function expression. so you can try this
document.getElementById("jouer").onclick = start;
also you don't need the click attribute in the element as you are targeting the DOM element above. if you want to trigger a function directly from some element then pass onclick attribute with the function call and you won't need to target like this
document.getElementById("jouer").onclick
reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

The only error i see is that you have a whitspace in the id selector in the input "jouer". this causes the script to not be able to grab the element. Otherwise, the error Uncaught SyntaxError: Unexpected token '<' means that you are trying to include a file (script) that it can't find.

Related

Am I missing a cast with querySelector('#element')?

I couldn't find identical answer to my question, so I decided to ask it by myself.
Im trying to select a HTML element with a specified ID in it.
This version works fine.
var button = document.getElementById('#submit');
function doSmth(){
console.log("clicked");
}
button.addEventListener('click', doSmth);
If I try to run the same code with querySelector:
var button = document.querySelector('#submit');
I get the following output:
Uncaught TypeError: button.addEventListener is not a function
Any ideas why same code outputs different return values?
This is the submit input field. It is part of the div container
<input id="#submit" type="submit">
Since the id have # use \\ to escape it
var button = document.querySelector('#\\#submit');
function doSmth() {
console.log("clicked");
}
button.addEventListener('click', doSmth);
<input id="#submit" type="submit">

Catch22 - HTML waiting for JS, JS waiting for HTML

I'm a newbie trying to write a JS/HTML report generator based on criteria which I submit in an HTML form. The plan eventually is to use PHP/mySQL to manipulate a database and return results but for now I'm just trying to build the HTML/CSS/JS and I've got stuck. I have attributed a JS function to a button in the <body> like so:
<input type="button" id="reportButton" value="Generate Report" onclick="showCriteria()">
I included a script in the <head> as follows:
<script>var showCriteria = function(){ My JS code...}</script>.
This function simply does some date manipulation and displays the result in a div on the same page like so:
document.getElementById("endDate").innerHTML = "to "+endDay+" "+endMonthName+" "+endYear;
But I get Uncaught TypeError: Cannot set property 'innerHTML' of null. So I searched the forum and discovered that this can sometimes be caused by not waiting for the window to load. So I wrapped the script as follows:
<script>
window.onload = function()
var showCriteria = function(){ My JS code...}
That solved the initial error but I then get Uncaught ReferenceError: showCriteria is not defined
It seems like I'm in a Catch22. I get the first error because the script is running before the window has loaded. I fix that by waiting for the window to load only to find that the HTML is waiting for my script to define my JS function.
Any advice gratefully received.
Report Generator screenshot
Window.load script
You've almost got the solution. At least you've got all the right elements.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};
This will make it so the button does not function until the page is ready.
You also need to remove the onclick from the button.
When you put the showCriteria function inside window.onload, please make sure it is accessible by the DOM, i.e. window.showCriteria.
<script>
window.onload = function()
window.showCriteria = function(){ My JS code...}
...
Beside using onclick on html, you can use add listener to listen the click event on that element.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};

Uncaught ReferenceError: errorCheck is not defined

I am trying to display an alert whenever the value inside of an input area is empty. I have done this in JavaScript and I keep getting the error:
"Uncaught ReferenceError: errorCheck is not defined"
It also says that my onclick is undefined. What is supposed to happen is when the user clicks the submit button is it supposed to look at the lastName input area and check if it is empty and if it is it will display an alert to the user.
HTML:
<input TYPE="button" VALUE="Submit" onClick="errorCheck()" />
JavaScript:
function errorCheck() {
if ((document.getElementsByID('lastName').value == "") {
alert("the last name area is empty")
}
}
I see two problems:
You have an extra ( in the if statement.
getElementsByID should be getElementById
This code works for me
function errorCheck() {
if (document.getElementById('lastName').value == "") {
alert("the last name area is empty")
}
}
The above code can be put in <script> tag inside <head> or <body> tag. If you want to put the code in an external .js file, you need to add a reference to the .js file.
Demo: http://jsfiddle.net/r7w1umnt/

thymeleaf:external js file

i'm trying to use an external javascript file in a thymeleaf project so i've done the following:
this is how the file is declared(i put this just before /body as suggested in many other posts)
<script type="text/javascript" th:src="#{/resources/lor.js}"></script>
this is the html function call
<a id="l2" th:href="'javascript:change2();'">
and this is the js file
function change1() {
document.getElementById("l1").setAttribute("class", "selected");
document.getElementById("l2").setAttribute("class", "");
};
function change2() {
document.getElementById("l1").setAttribute("class", "");
document.getElementById("l2").setAttribute("class", "selected");
};
however i get the following error "Uncaught ReferenceError: change2 is not defined" from firebug.
i've also tried
function change2() {
document.getElementById("l1").className="";
document.getElementById("l2").className="selected";
};
and i'm getting "Uncaught TypeError: Cannot set property 'className' of null"
it seems like the js file is not even processed.any solution?
thanks in advance
I would suggest that you used an event handler instead of a function call on the href attribute.
So you may change your anchor link to this:
<a id="l2" href="javascript:void(0);">l2_Link</a>
To add a click event, you have to make use of the window.onload event as Rooster proposed.
window.onload = function (){
document.getElementById ("l2").addEventListener ("click", change2, false);
}
You can view a working example of this at: http://jsfiddle.net/RKSZ2/1/

javascript onclick failing on a function call

I have this html...
<a onclick="search.analysisSelect('2');" href="javascript:void(0);">A Product</a>
...And whenever I click that link in the browser (IE, FF, and Chrome), it fails. It tells me that the function does not exist. However, if I type that exact function call into the console of firebug, it runs fine. So the function does exist.
Exact error message: "search.analysisSelect is not a function"
I have recently changed the "search" object name to "searchTab" and the onclick works fine.
Why is the onclick failing for the search object? I am baffled...
Here is the search object. This is stored in a separate js file loaded when the page loads.
var search = {
analysisSelect: function(pub) {
$("#tabs").tabs("select", "#analysis");
analysisGrid.refreshSlickGrid(pub, '0', '1', '0');
}
};
Oh, I forgot to mention that I also have an init() funciton defined in the search object, which is called on an onclick event for another html element, and that fires off with no issues. Wtf...
Where did you define search.analysisSelect()? It should be defined before the anchor tag.
generally using inline javascripts is not a good idea, consider using an external javascript file and bind that function to the anchor onclick event like this:
window.onload = function() { // ensures that the document is loaded before finding the anchor element
// assign an Id to the anchor tag like this: <a id="idOfAnchorTag" href="#">A Product</a>
var elem = getElementById('idOfAnchorTag');
elem.onclick = function() {
search.analysisSelect('2');
}
}
There is some strange javascript voodoo going on in the inline event handler. search is not being resolved to window.search, it is hitting something else and I don't know what it is.
See http://jsfiddle.net/yPhZ8/
However, I can tell you how to fix it. Use window.search instead.
<a onclick="window.search.analysisSelect('2');" href="javascript:void(0);">A Product</a>
See: http://jsfiddle.net/yPhZ8/1/
I just had this exact problem today. Turns out, you can't have an HTML element with an ID the same as the function.
Don't ask me why, I'd just say it has something to do with extremely lazy parsing.
My Example:
<dd style="margin-left: 2px;"><input type="button" name="info[add_benefit]" id="add_benefit" value="{L_ADD_BENEFIT}" class="button2"
style="width: 100%;" onclick="add_benefit();" /> </dd>
The onclick method would return an error saying that the function didn't exist. Apparently it thought the button itself was the function, but the button was a button, hence the error.

Categories

Resources