How to detect submit form button was clicked - javascript

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

Related

How to Make button disabled after 1h and auto re-enable after time is over?

I'm trying to get this button to deactivate on click for an 'x' amount of time and auto re-enable after the time is over. Also, even if the page is refreshed this should stay disabled if the time has not expired in the localstorage. This is what i have so far but the button keeps on appearing after i refresh the page even though the time was not over yet. Please help, been trying for some days now trying to solve this problem.
const btns = document.querySelectorAll('.btn');
const getBtnState = function (btns) {
[].forEach.call(btns, function(btn) {
if (window.localStorage.getItem(btn.id) == 'disabled') {
btn.disabled = true
}
})
};
const resetBtnState = function (btns) {
[].forEach.call(btns, function(btn) {
btn.disabled = false
window.localStorage.setItem(btn.id, '')
})
};
var timeout_time = 10;
var time_remaining = 0;
if(localStorage.getItem('timeout_time')==null){
run_timeout(timeout_time);
}
else{
run_timeout(localStorage.getItem('timeout_time'))
}
setInterval(function(){
time_remaining = localStorage.getItem('timeout_time');
if(time_remaining > 1 || time_remaining != null){
localStorage.setItem('timeout_time', time_remaining - 1);
}
}, 1000);
function run_timeout(time){
[].forEach.call(btns, function(btn) {
btn.addEventListener('click', function (e) {
btn.disabled = true
window.localStorage.setItem(btn.id, 'disabled')
alert('Your next vote will be available in 24h');
})
})
}
setTimeout(function(){
localStorage.removeItem('timeout_time');
localStorage.removeItem(btn.id, 'disabled');
}, time * 1000);
localStorage.setItem('timeout_time', time);
getBtnState(btns);
<button class="btn" id="myBtn" onclick="add1()" style="display: visible">Click for
+1</button>
I couldn't test your code locally, so I wrote the following code for you to understand better on how to accomplish this.
Explanation: We want to listen to DOMContentLoaded event and check if our button is currently disabled, if so, we disable the button.
<button class="btn" id="myBtn" >Click for +1</button>
<script lang="js">
const BUTTON_TO_DISABLE = document.getElementById("myBtn");
/**
* This is the actual event that will be called when the user clicks on the button
* #param {Event} e
*/
const clickEvent = (e) => {
// Get the id of the button that was clicked, we need this so we can recognize the button
const buttonId = e.target.id;
//Set the button to disabled in the local storage
window.localStorage.setItem(buttonId, 'disabled');
//Disable the button
e.target.disabled = true;
//Notify the user that the button was clicked
alert('Your next vote will be available in 24h');
}
BUTTON_TO_DISABLE.addEventListener("click", clickEvent);
/**
* Listen to document load event
*/
document.addEventListener("DOMContentLoaded", () => {
//Get the button id
const buttonId = BUTTON_TO_DISABLE.id;
//Check if the button is disabled in the local storage
if (window.localStorage.getItem(buttonId) === 'disabled') {
//Disable the button
BUTTON_TO_DISABLE.disabled = true;
}
});
</script>

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.

How to disable button while form is being created and to prevent duplicate form

I am trying to make it so that a "Submit" button is disabled when submitting and forwarding data from a form. This is to prevent the user from create multiple copies of the form when rapidly clicking the button when the initial data that was inputted is being saved.
One approach I tried was adding a debouncer to the JavaScript function that handles the submit button operations. However if the user continues to click the button after 5 seconds, the duplicate is still created.
I think a better approach would be to disable the button while the data is being submitted and give an indication to the user that the data is in the state of being saved, and after completion, reenable the button.
Here is the javascript code for context:
setupFormIO: function(submissionFunction) {
var $this = this;
var submitFunc = submissionFunction;
var labelText = "Submit";
if ($this.projectData && !this.readonly) {
labelText = "Save";
}
var submits = FormioUtils.searchComponents($this.template.components,
{
"type": "button"
}
);
if (submits) {
_.each(submits, function (component) {
component.label = labelText;
//
var timer;
if (timer) {
clearTimeout(timer);
}
//
if ($this.readonly) {
$("#" + component.id + " > button").on("click", function(evt) {
evt.stopPropagation();
location.assign("/project/ProjectHome.aspx");
timer = setTimeout(process, 5000); //
});
}
});
}
Adding the following bits of code at strategic locations of the script that handle operations during and after the submit button is clicked helped create the desired effect.
beforeSubmit: function (submission, next) {
const btns = document.querySelectorAll('.btn');
for (const btn of btns) {
btn.disabled = true;
}
$this.isSubmitting = true;
console.log("button disabled");
if (submits) {
_.each(submits, function (component) {
console.log("renabled");
for (const btn of btns) {
btn.disabled = false;
}
$this.isSubmitting = false;
console.log("button renabled");
});
}
However this was disabling and enabling every single button on the page. Ultimately the following jquery method was used because it specifically targets the submit buttons only.
if (submits) {
_.each(submits, function (component) {
$("#" + component.id + " > button").prop('disabled', true);
});
}
window.axios.post($this.baseUri + '/validate',
submission.data)
.then(function (d) {
next();
})
.catch(function (e) {
var message = "Validation Failed:";
$this.isSubmitting = false;
if (submits) {
_.each(submits, function (component) {
$("#" + component.id + " > button").prop('disabled', false);
});
Also wanted to note that after the submit button is clicked, the page reroutes to a summary page to prevent the submit button from being clicked again.

My event listener activates all elements below. How can I fix it?

initAccordion(){
const thisProduct = this;
const clickTrigger = document.querySelectorAll(select.menuProduct.clickable);
for (let click of clickTrigger) {
click.addEventListener('click', function(){
event.preventDefault();
console.log('click');
thisProduct.element.classList.toggle(classNames.menuProduct.wrapperActive);
const allActiveProducts = document.querySelectorAll(classNames.menuProduct.wrapperActive);
for(let active of allActiveProducts){
if (active !== thisProduct) {
active.classList.remove(classNames.menuProduct.wrapperActive);
}
}
});
}
}
When event is triggerd on one generated element all elements below are getting class active. How can I prevent that?
event.stopImmediatePropagation();
event.stopPropagation();
Add this after event.preventDefault(), it will allow only one selector(which comes first or where you click) to trigger, not all.

stopPropagation() on submit not working

I'm having trouble with stopping the propagation of a submit inside a form. It appears that no matter where I click within the webpage an event is fired - how can it be fixed to only fire upon clicking the submit button?
document.addEventListener('DOMContentLoaded', bindButtons);
function bindButtons() {
var buttons = document.getElementsByTagName('submit');
Array.prototype.forEach.call(buttons, addEventListener('click', function(event) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.addEventListener('load', function(event) {
// do stuff
})
event.preventDefault();
event.stopPropagation();
req.send(null);
}))
}
Submit is not a valid tag, you can find your submit buttons with the following code:
var submitButtons = document.getElementByTagNames('button').filter(button => button.getAttribute('type') === 'submit');
or, more verbose:
var submitButtons = document.getElementByTagNames('button').filter(function(button){
return (button.getAttribute('type') === 'submit')
);
Added each submit to the same class then stored those in an array using getElementsByClass() and iterated over that.

Categories