This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 6 years ago.
I keep getting this error when i inspected the element of my button. The button is suppose to give a print view to page.
HTML Code:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
Javascript Code:
function printProducts(){
window.print();
}
Attached here is my code live in jsFiddle:
https://jsfiddle.net/PochMendoza/scj0q0dk/
"In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers."
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
---Niet The Dark Absol
For your example, you want to define the onclick method of a button. That's really easy with JavaScript, we just need to give the button an id in the HTML, so that we can find it in our JavaScript code.
Change this:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
To this:
<button id="myButton" class="hidden-print">Print Products</button>
Note that we no longer need the onclick="printProducts()" part anymore.
Now we need to set the printProducts function to run when the button is clicked. This can be done like so:
document.getElementById('myButton').onclick = printProducts;
Start edit
This code needs to be placed in the onload function though, to properly run.
Do that like so:
window.onload = function() {
document.getElementById('myButton').onclick = printProducts;
}
End edit
And the printProducts function remains the same.
Working JSFiddle
document.getElementById('myButton').onclick = printProducts;
function printProducts(){
window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>
Related
Yesterday I made this post: Button Function Working Without Click, trying to figure out why my code wasn't working for a document.getElementById("examplebutton").onclick = function();, but the problem is I can't set parameters on the function() because the parentheses would make the button auto-fire.
Does anyone know how to put parameters in a line of code similar to this:
<button id="button" onclick="function1">BIG BUTTON THING</button>
document.getElementById("button").onclick=function2
(I would want the parameter set to be for function 2)?
What you need is a closure. Just wrap you function call into another one.
var myButton = document.getElementById("examplebutton");
myButton.onclick = function(){
myButtonFunction('some parameters');
};
function myButtonFunction(param){
console.log(param);
}
To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!
I'm trying to call a js function when a button is clicked in html, but it won't run. The button is being clicked, because I tested a prompt and it showed up, but when we put a function there it wont run...
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = <c:outvalue= "${lesson.GetNextLesson()}"/>";}
Then I call the method in a button
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next"/>
We've found that when a function gives an error, javascript declares the entire function as dead, but I don't know the error
This works:
You had a couple syntax issues that was killing your function- including not completely wrapping your innerHTML content in quotes - and your Button element was not using the correct syntax.
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next">Next</button>
<script>
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= ${lesson.GetNextLesson()}/>"
};
</script>
Fiddle
Errors corrected in the 2nd line of function:
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= '${lesson.GetNextLesson()}'/>";
}
This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 7 years ago.
I'm trying to target a button I've created by pressing another button. My code technically works, but due to the size of what I'm doing, I'm trying to put the function of the second button press in another js file. That where I'm running into problems. My code is below.
$("#webCoding").on("click", function() {
if ( $( ".webCodingID" ).length ) {
return false;
}
picture.attr("src", "img/webCoding.jpeg");
$(".target").empty();
$(".jumbotron").hide();
var buttonGroup = $('<div role="group" aria-label="...">').addClass('btn-group-vertical center-block')
var buttonPhilosophy =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Design Philosophy")
var buttonStack =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Visit My Stack Overflow Account")
var buttonGithub =$("<button type='button' id='git'>").addClass("btn btn-default btn-lg").append("Look at what I've been doing on Github")
var webCodingID =$("<div>").addClass("trainingID")
$(buttonGroup).append(buttonPhilosophy).append(buttonGithub).append(buttonStack);
$('.target').append(buttonGroup).append(webCodingID);
// code for pressing created button is below.
$("#git").on("click", function() {
prompt("herro");
});
});
but I put this in another file (and get rid of the same code in the original js file), and nothing happens.
$(document).ready(function(){
$("#git").on("click", function(){
prompt("jungle boogie");
});
I can't figure out why. The js file is linked to my main page, I just can't get it to recognize buttons created by JS in another file.
You should bind the on to the body like so:
$("body").on("click", "#git", function(){
That should solve your problem I believe :)
I have a script, which I'm using to try and display only one section of a webpage at a time.
function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}
Currently, I'm using buttons to change which section is displayed.
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");
However, when I load the page, the following happens:
I see the function attached to each button activate once in sequence in the console.
The page refuses to respond to further button inputs.
Testing with the console shows that showMe() and the functions it calls still all work properly. I'm sure I'm making a very basic, beginner mistake (which, hopefully, is why I can't find this problem when I Google/search StackOverflow/read event handling docs), but I'm at a loss for what that mistake is. Why would my script assume my buttons are clicked on load, and why won't it let me click them again?
You're calling the function an assign the value to onclick property instead of attach the function, try defining your onclick property as:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
Try the follow jsfiddle:
function showMe(id){ // some stuff..
console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>
Hope this helps,