Button Text not updating within eventListener - javascript

Button text is not updating when the event is triggered. This is a submit event but I've also tried a click event. I've also tested the code outside of the event listener and it works correctly. So the problem seems to be within the event listener.
Here is the code:
let addToCartForms = document.querySelectorAll(".bundle-builder--add-to-bundle-form");
addToCartForms.forEach((el)=>{
let btn = el.querySelector('.add-to-cart');
let btnText = btn.innerText;
el.addEventListener("submit",(e)=>{
btn.innerText = "added"
});
})

Both click and submit work. Maybe the form is submitted so you can't see the effect?
let addToCartForms = document.querySelectorAll(".bundle-builder--add-to-bundle-form");
addToCartForms.forEach((el) => {
let btn = el.querySelector('.add-to-cart');
let btnText = btn.innerText;
el.addEventListener("submit", (e) => {
btn.innerText = "added"
});
})
<form class="bundle-builder--add-to-bundle-form">
<button class="add-to-cart">click</button>
</form>

Maybe this jQuery solution could work.
$('body').on('submit', '.bundle-builder--add-to-bundle-form .add-to-cart', function(e){
(e).preventDefault();
(this).text('added');
setTimeout(function() {
(this).submit()},500)
})

Related

javascript onclick set to false

document.getElementById("btn2").onclick = false;
I did this to stop getting on click event after the first one and when I want to set it back to normal
document.getElementById("btn2").onclick = True;
it does not take click events
You could always disable the button, like this:
document.getElementById("btn2").disabled = true;
This sets the disabled attribute to true, therefore stopping the onClick function from being called when the user clicks the button.
Declare a variable boolean and change using logical not operator (!: see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT), example:
let toggle = true;
let button = document.querySelector('button');
let result = document.querySelector('span');
button.onclick = () => {
toggle = !toggle;
result.textContent = `Your switch to ${toggle}`;
}
<button>Click me</button>
<span></span>
You may not set onclick event as True instead try this way.
const setEvent = (enable) => {
if(enable){
document.getElementById("btn2").addEventListener('click', onClickEvent);
}
else{
document.getElementById("btn2").removeEventListener('click');
}
}
function onClickEvent(){
//Your actual event when clicking the button
}
//Now enable or disable the event as follows
setEvent(true); //Will attach the event
setEvent(false); //Will remove the event
Make sure you call setEvent(true) once only, because it can attach multiple events.

Javascript alert not displaying at all

I have this function that should I think trigger an alert whenever one of the buttons in my page gets clicked, however nothing happens and if I open the console on the webpage, no errors show. why is it?
document.addEventListener('DOMContentLoaded' , () => {
document.querySelectorAll('.new-button').forEach (button => {
button.onclick = () => {
const buttonName = button.innerHTML;
alert(`you have selected the button! ${buttonName}`);
}
});
});
I am using the ES6 version of JavaScript if that's any help.
If you dynamically add elements, you have to attach the eventListener to some ancestor element that was statically added. documentworks, but you can add more specific elements for performance. This concept is called delegate listener.
document.addEventListener('click',function(e){
if(e.target && e.target.matches('.new-button')){
const buttonName = e.target.innerHTML;
alert(`you have selected the button! ${buttonName}`);
const newButton = document.createElement('button');
newButton.classList.add('new-button');
newButton.innerHTML = 'click me!!';
document.getElementById('container').append(newButton);
}
});
<div id="container">
<button class="new-button">click me!</button>
</div>

favorite script with local storage don't work

I want to add data-id from a button in favorite list.
I tried few solution but the click action is never detected in console .
html code is
<button class="icon-plus-circle i-circled i-small addToCart" date-id="myId" data-name="myName"></button>
js code is
button.addEventListener('click', function (){
var id = $(this).attr('data-id');
var name = $(this).attr('data-name');
console.log(id);
let Fav = {
id : id ,
name : name
};
let liste_json = JSON.stringify(Fav);
localStorage.setItem('listeFavoris', JSON.stringify(liste_json));
} )
You need to select the button
const button = document.querySelector('button');
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('click detected');
});
<button>Click Me</button>
PS - You have added click listener using javascript and have jQuery code inside. Don't mix up two, stick with one.

How to detect submit form button was clicked

I've two button on submit form.
1. Add to Cart Button
2. Buy Now Button
I need to add disable class if the button was clicked,
submitForm: function (form) {
var addToCartButton, buyNowButton, self = this;
if (form.has('input[type="file"]').length && form.find('input[type="file"]').val() !== '') {
self.element.off('submit');
// disable 'Add to Cart' button
addToCartButton = $(form).find(this.options.addToCartButtonSelector);
buyNowButton = $(form).find(this.options.buyNowButtonSelector);
if(addToCartButton){
addToCartButton.prop('disabled', true);
addToCartButton.addClass(this.options.addToCartButtonDisabledClass);
}else if(buyNowButton){
buyNowButton.prop('disabled', true);
buyNowButton.addClass(this.options.buyNowButtonDisabledClass);
}
form.submit();
} else {
self.ajaxSubmit(form);
}
},
Try it like this (JQuery):
$(".classNameOfButton").click(function(){functionName(this)});
Pure Javascript, here you go :)
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector("button");
button.addEventListener("click", (e) => {
e.target.disabled = true
})
});
wait for DOM content to get loaded (probably not necessary in your case as it will be part of larger codebase
get button element you need
addEventListener for click to that element
set disabled to true
About event.target
https://developer.mozilla.org/pl/docs/Web/API/Event/target
Codepen:
https://codepen.io/pen/
JS:
// Disable default Event (Browser reloading..)
const formElement = document.getElementByID("formID");
formElement.addEventListener("submit", () => {
event.preventDefault();
});
const button1 = document.getElementByID("button1");
button1.addEventListener("click", (event) => {
// do something...
e.target.classList.add("disabled");
});
const button2 = document.getElementByID("button2");
button2.addEventListener("click", (event) => {
// do something...
e.target.classList.add("disabled");
});
Prevent Default Action of a form submit button (reload site)
get both buttons and attach an "click" event listener
If clicked add "disabled" class

Unable to attach click event to a dynamically created button

I have created a javascript function to dynamically create a button
function btn(d) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(d);
btn.appendChild(t);
btn.className = "myButton";
btn.onclick = alert('hello');
document.body.appendChild(btn);
}
when this function is called, alert is poping up even if button is not clicked. I want the alert when button is clicked. May be i am missing something. Please help. Thanks
you are calling the alert function not assigning a function
alert('hello'); // evals immediately.
btn.onclick = function () {
alert("Hello World"); // gives the button a click handler
// which can be called when clicked
};
Try doing it with jQuery, like so (per your jQuery tag on the question):
function btn(d) {
var btn = $('<button/>').addClass('myButton').text(d).appendTo('body').click(function (e) {
alert('hello');
})
}
onclick should look like:
btn.onclick = function(){alert('hi');};
You are assigning the return value of alert('hello'); to the onclick, while it is expecting a function. The correct way without jQuery would be
if (btn.addEventListener)
btn.addEventListener ('click',function(){ alert('hello');}, false);
else if (btn.attachEvent)
btn.attachEvent ('onclick',function(){ alert('hello');});

Categories