How to add onClick attribute to a button with JS? - javascript

How can I add onClick attribute to this button using JS?
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt">BUY NOW</button>

You can do it using Jquery:
"your element".addEventListener('click', function(){
alert('hey');
}, false);

you can use the JS function .addEventListener(), Here you'll find a well done explenation of It.
What I sugger you to do is to add an Id to your button tag and then use the document.getElementById() (if you don't know what this JS function does read this) to find your button and apply to It the .addEventListner() function to add a click behaviour.
I made a simple code example below, take a look at It and let me know if this answer is what you're searching for.
document.getElementById('myButton').addEventListener('click', () => {
document.getElementById('myButton').classList.toggle('toggled');
});
button {
width: 100px;
height: 50px;
background: #ccc;
border: 0;
outline: 0;
}
button:hover {
cursor: pointer
}
button.toggled {
background: red;
}
<html>
<head></head>
<body>
<button type=submit id="myButton">
CLICK ME
</button>
</body>
</html>

If you want to do it in js, you will have to either use .addEventListener() function or .onClick() function that are triggered whenever the button is clicked
you can also use the .onClick inside of your html
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt" onClick="function_name">BUY NOW</button>
sidenote: if you want to access the button element inside your javascript you can add an Id to your button tag and then use the document.getElementById() or use let var = document.getElementByClass() but be aware to use var[0] to access the button element in case you filtered it by class

Related

document.getElementById() not working as intended with multiple ids

I have an issue with document.getElementById(). Basically I have different forms each one with a different id and I'm using a bit of Javascript to replace some classes and add dinamically file name after upload.
That should be really easy, but I don't know why even if the ids are totally unique I get a weird behavior: whatever is the form in which I submit a file javascript will apply changes always on the first of them.
function spinnerLoad(){
document.getElementById('file-name[[${id}]]').textContent = this.files[0].name;
document.getElementById('spinner[[${id}]]').classList.replace('fas', 'spinner-border');
document.getElementById('spinner[[${id}]]').classList.replace('fa-file-upload', 'spinner-border-sm');
document.getElementById('uploadForm[[${id}]]').submit()
}
/*I'm using Bootstrap for my styling rules*/
/*${id} variable is server-side and it's there to make unique each form, I'm using Thymeleaf template engine*/
<form th:id="'uploadForm'+${id}" method="post" enctype="multipart/form-data" th:action="#{/upload/{id} (id=${id})}">
<label for="file-upload" class="btn btn-outline-success">
<span th:id="'spinner'+${id}" class="fas fa-file-upload"></span> <b>Upload file:</b> <i th:id="'file-name'+${id}">No file selected</i>
</label>
<input id="file-upload" type="file" name="multipartFile" accept="application/pdf" style="display: none" th:onchange="spinnerLoad()"/>
</form>
I googled the problem but I didn't manage to find a specific answer to my issue, so that's why I'm here bothering you.
I hope someone can help my figure this out, thank you.
You get a lot of repeating code and that can be hard to maintain. Here I placed the event listener on the the parent <div> to all the buttons. Then I need to test if is a button. And there is no need for an id for each button.
Actually, if you are just replacing a class name you don't even need to do the test (if()), because replace() will only do the replacement when the old value is present. This should be fine:
buttons.addEventListener('click', e => {
e.target.classList.replace('btn-success', 'btn-danger');
});
But here is the full example with the test:
var buttons = document.getElementById('buttons');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
e.target.classList.replace('btn-success', 'btn-danger');
}
});
.btn-success {
background-color: green;
}
.btn-danger {
background-color: red;
}
<div id="buttons">
<button class="btn-success">Button 1</button>
<button class="btn-success">Button 2</button>
<button class="btn-success">Button 3</button>
</div>
You're missing the css that would make this work, but otherwise your example is functional. However, it can be done more simply by working on the buttons as a class instead of individually.
var btns = document.getElementsByClassName("btn");
var addDanger = function(){
this.classList.replace('btn-success', 'btn-danger')
};
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', addDanger, false);
};
.btn {height:20px; width: 50px;}
.btn-success {background-color:green}
.btn-danger {background-color:red}
<button id="btn1" class="btn btn-success"></button>
<button id="btn2" class="btn btn-success"></button>
<button id="btn3" class="btn btn-success"></button>

How to get event target/this without putting the event listener in the HTML tag? [duplicate]

This question already has answers here:
Get clicked element using jQuery on event?
(6 answers)
Closed 5 years ago.
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use
$(document).ready(function(){})
I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?
//$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>
Thanks in advance!
PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.
PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D
PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)
Firstly you need to define function() in a click function so it should look like this:
$("button").click(function() {
//code to execute here
});
Instead of this:
$("button").click(//code to execute here);
When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.
To use this you also need to call it as $(this) not just this.
This should work.
//$(document).ready(function() {
window.onload = startup();
function startup() {
console.log("window loaded");
$("img").hide();
$("button").click(function() {showImage(this)});
}
function showImage(e) {
console.log("onside eras");
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:
var chosen = $(this).prop('value');
I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.
UPDATE
Just saw your commented out code:
$("button").click(showImage(this)); // When a button is clicked
// call the function returned by showImage(this).. err it doesnt return
// a function so it fails.
you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.
It should actually be:
$("button").click(showImage); // when a button is clicked
// call the function showImage with this=<clicked button> and param=event
and this will be automatically set inside the function as event.currentTarget
$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = $(this).prop('value');
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
$('.myclass').on('click', showImage);
});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>

div into a js button [duplicate]

This question already has answers here:
Add click event on div tag using JavaScript
(6 answers)
Closed 5 years ago.
I have a <div> that I have formatted very carefully to look nice, and I need to make it have the functionality of a button. How would I go about doing this?
You can give that div tag a onclick function as follows.
function myfns() {
console.log("Clicked")
}
<div id="btn" onclick="myfns()">Click</div>
First recommendation is to use a <button> instead. You can style that however you want as well. If that is not an option for some reason, you'll have to do a few different things to create a proper button out of a div element (to ensure that it works with keyboard and screen readers).
Add click handler. Eg btn.addEventListener('click', clickHandler);
Add enter key handler. Eg btn.addEventListener('keyup', keyHandler);
Add button role. role="button"
Add it to tab order: tabindex="0"
var buttons = document.querySelectorAll('.btn');
buttons.forEach(function (btn) {
btn.addEventListener('click', function(e) {
console.log('clicked');
});
btn.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
console.log('keyup');
}
});
});
.btn {
display: inline-block;
background: #eee;
border: 1px solid #aaa;
padding: 6px;
cursor: pointer;
}
<div class="btn" role="button" tabindex="0">My Button</div>
<div class="btn" role="button" tabindex="0">My Button</div>
<div class="btn" role="button" tabindex="0">My Button</div>
document.getElementByID("#divID").addEventListenet('click',()=>{
//write your logic
})
handle all button event similarly
e.g. doubleclick etc
Like if you have div
<div class="demo" >
....
</div>
And If you are using javascript
document.getElementsByClassName('demo')[0]
.addEventListener('click', function (event) {
// do something
});
using jquery u can do like
$(".demo").click(function(){
//do something
});

How to toggle show and hide for two forms present in the same div?

I have two forms present in a div, form1 is visible when the page loads, and if I click the next button form1 is hidden and form2 is shown, which is working as expected.
Now I want to achieve the reverse of above scenario which is on click of a back button, form2 should be hidden and form 1 is shown.
Here's javascript code I have so far..
function switchVisible() {
document.getElementById("disappear").innerHTML = "";
if (document.getElementById('newpost')) {
if (document.getElementById('newpost').style.display == 'none') {
document.getElementById('newpost').style.display = 'block';
document.getElementById('newpost2').style.display = 'none';
} else {
document.getElementById('newpost').style.display = 'none';
document.getElementById('newpost2').style.display = 'block';
}
}
}
So basically I am looking for a way to achieve toggle functionality for two forms present in the same div using javascript and setting their display property.
Use a variable stepCount and then according to the value of count display appropriate form.
Like initialise the stepCount with 0, then on click of next increment it by 1 and check condition if stepCount is 1 show second form
Similarly from there if back button is pressed decrement the stepCount by 1 and check condition if stepCount is 0 show first form
Do all this on click of appropriate button click event
Make two button elements
<button id="next"></button>
<button id="back"></button>
You can use jquery (or plain javascript) for this, but I personally prefer jquery.
$("#next").click(function {
$("#newpost").hide();
$("#newpost1").show();
});
$("#back").click(function {
$("#newpost").show();
$("#newpost1").hide();
});
(Here 'newpost' and 'newpost1' are the id's of the two form elements)
You can use a similar format if you want to use plain javascript.
Add this
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</head>
You can also use link button and provide URL for particular form in this and hide back link button when click on back that time show only Next button.
e.g.
Next
Previous
$("#btnNext").click(function {
$("#btnNext").hide();
$("#btnPrevious").show();
});
$("#btnPrevious").click(function {
$("#btnPrevious").show();
$("#btnNext").hide();
});
You can use toggle function to show hide div.
$('#newpost2').hide();
$("#Toggle").click(function() {
$(this).text(function(i, v) {
return v === 'More' ? 'Back' : 'More'
});
$('#newpost, #newpost2').toggle();
});
.one {
height: 100px;
width: 100px;
background: #eee;
float: left;
}
.two {
height: 100px;
width: 150px;
background: #fdcb05;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='Toggle' class='pushme'>More</button>
<div class="one" id='newpost'>
<p>Show your contain</p>
</div>
<div class="two" id='newpost2'>
<p>Hide your contain</p>
</div>
This fiddle for button disappear:
$("#next").click(function()
{
$("#next").hide();
$("#back").show();
});
$("#back").click(function() {
$("#back").show();
$("#next").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" id="next" value="Next"/>
<input type="button" id="back" value="Back"/>
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="switchVisible();">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="previousVisible();" >BACK</button>
simply use this jquery:
function switchVisible()
{
$("#newpost").hide();
$("#newpost2").show();
}
function previousVisible()
{
$("#newpost").show();
$("#newpost2").hide();
}
your updated fiddle
Or you may do like this:
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="form(1);">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="form(2);" >BACK</button>
function form(a)
{
if(a==1)
document.getElementById("newpost").style.display="none";
else
document.getElementById("newpost2").style.display="block";
}

jquery toggle open all div s on one click

Please take a look at below codes, for whatever reason I am unable to open one div only when I click on the edit link, it opens all divs when I click the edit link.
jQuery
$(document).ready(function () {
$("input:button[name='uploadboy']").click(function () {
$(this).parent().children('.uploadboy').slideToggle(200, 'swing');
});
});
HTML
<div style="overflow:auto;" class="links-box ">
<p style="float:left; width:250px;" id="links">
<input type="button" name="uploadboy" id="uploadboy" value="Uploaded" title="Uploaded" style="text-decoration:none; color: white; text-shadow:none; background: #0692fe; float:left;" class="g-button">
</p>
</div>
<div class="uploadboy" width: 600px;min-height:50px;background-color: #F2FDD7;border-radius: 10px;border: 1px solid #8EBD43;">
<p>content</p>
</div>
<div style="overflow:auto;" class="links-box ">
<p style="float:left; width:250px;" id="links">
<input type="button" name="uploadboy" id="uploadboy" value="Uploaded" title="Uploaded" style="text-decoration:none; color: white; text-shadow:none; background: #0692fe; float:left;" class="g-button">
</p>
</div>
<div class="uploadboy" width: 600px;min-height:50px;background-color: #F2FDD7;border-radius: 10px;border: 1px solid #8EBD43;">
<p>content</p>
</div>
example in jsFiddle
Use the below script, .find method only searches for the descendants (http://api.jquery.com/find/).
$(document).ready(function () {
$("input:button[name='uploadboy']").click(function () {
$(this).parent().parent().next('.uploadboy').slideToggle(200, 'swing');
});
});
As I mentioned in my comment above, IDs must be unique. That said, try this:
$("input").click(function () {
$(this).slideToggle(200, 'swing');
});
jsFiddle example
What I initially see here that's an issue is that you have 2 input buttons with the same id. While this may not be the overall issue, you still can't have 2 elements with the same id. I also am not sure if this is just generic code you cleaned to ask a question, but your selectors seem pretty complicated. You attach the .click event to both input buttons, then you go to the buttons parent, which is the paragraph, then you go the child object which is the button. You are essentially going from point one spot, up a level, then back down a level. When the click handler is attached to the button, anytime you click a button, you can reference $(this) to refer to the button.
<input type="button" name="uploadboy" id="button1" />
<input type="button" name="uploadboy" id="button2" />
$(document).ready(function(){
$("input:button[name='uploadboy']").click(function () {
$(this).SlideToggle(200, 'swing');
});
});
If you look at the function that is ran when the input button is clicked, it simply refers to the $(this) object. This is a benefit of jquery and $(this) is the specific button that you clicked. Even if there are 20 buttons on the page, whatever button is clicked will be this. So in the above example, the button clicked will have the slide toggle occur. You could also navigate the dom off of this if you need to move around like before.

Categories