Function keeps running repeatedly Jquery - javascript

I have a stupid simple Jquery .js file I'm busy creating and I'm getting stuck on the first step.
I currently have it setup as shown below and yet every time I click the only button on the page (submit button for a login page), it reloads the entire page and runs the first function again.
How do i get the function to only run once
$(document).ready(function() {
//
// FUNCTIONS
//
function AllFade() {
//Hide everything
$('div').hide()
//Fade Everything in
$('div').fadeIn(1000);
//Hide All Alerts
$('.alert').hide();
}
function LoginCheck() {
//Check username and pass
}
// EVENTS
//START SEQUENCE
AllFade();
//Login check on submit
$('.btn').click(function() {
LoginCheck();
})
});
!! EDIT !!
The button's coding is this exactly:
<button class="btn btn-large btn-primary">Sign in</button>
Would that still cause a reload?

You need to prevent the submit (event) of the form with .preventDefault() so it will not do the default behaviour: submit the form and reload the page.
$('.btn.btn-large.btn-primary').click(function(event) {
//if only button on page you can have just $('button')
event.preventDefault()
LoginCheck();
})
You can also add type="button" if you do not want to use the button as a submit button, because the button element has a default type of submit:
<button type="button" class="btn btn-large btn-primary">Sign in</button>
You can read more here:
jQuery docs: .preventDefaul()

Add an event in there and use .preventDefault()to prevent the page from reloading.
$('.btn').click(function(e) {
e.preventDefault();
LoginCheck();
});

Related

How do I make my page stop refreshing after clicking submit button?

Trying to make popup window with form in it. When clicking submit, page is refreshing. How can I prevent it? My e.preventDefault is not working
modalsubmit.addEventListener('submit', function(e) {
e.preventDefault();
modal.classList.toggle('overlay_opened');
profilettl.textContent = modalname.value;
profdesc.textContent = modaldesc.value;
});
I assume you've added the submit event listener to the button and not the form. Check this out and it should work.
const modalsubmit = document.querySelector('form');
modalsubmit.addEventListener('submit', function(e) {
e.preventDefault();
});
<form>
<button type="submit">submit</button>
</form>
Use the e.stopPropagation() to interrupt the default behavior
https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

JavaScript - beforeunload override on form submit

I have the following script on my page to help users stop closing the window accidentally and to notify them if they're navigating away from the page.
<script>$(window).on( 'beforeunload.edit-post', function() {return true;});</script>
However, when a user submits a form on my page, I don't want this pop up to trigger. I tried adding .preventDefault(); to it but it didn't work. How do I make it so the beforeunload pop up doesn't appear when the user submits the form with the button?
<script>
function submit() {
$(window).on('beforeunload.edit-post').preventDefault();
$("#form").submit();
}
</script>
<form id="form"><input name="example" value="example"></form>
<button onclick="submit()">Submit</button>
The submit() function should remove the beforeunload listener.
function submit() {
$(window).off('beforeunload.edit-post');
}
It doesn't need to call $("#form").submit(), that happens by default unless it calls event.preventDefault();

Reactjs: page refreshing upon `onClick` handle of Button?

I have the following block inside my render() (which is a Bootstrap Button: https://react-bootstrap.github.io/components.html#buttons-options):
<Button type="simpleQuery" onClick={this.handleEntailmentRequest.bind(this)}>
Query
</Button>
and the following function:
handleEntailmentRequest() {
console.log("handle request ");
}
Whenever I click on the button I can see that the "handle request" question appears in the console log, but suddenly disappears. My understanding is that something is causing the page to refresh. Any opinons where I am going wrong?
The default button action is to submit the form.
If you don't need that - you need to prevent that:
handleEntailmentRequest(e) {
e.preventDefault();
console.log("handle request ");
}
References:
MDN - Event.preventDefault()
The full solution for the issue of the page reloading will be:
<Button type="simpleQuery" onClick={(e) => {this.handleEntailmentRequest(e)}}>
Query
</Button>
handleEntailmentRequest(e){
e.preventDefault();
//do something...
}
You can prevent the default behavior as suggested by zerkms or
Just add type="button" in button tag.
Eg: this.showSomething('all')}>All
Yes! That did worked!
If your react-app gets refreshed unexpectedly then, you should pass (e) as an event argument and then use e.preventDefault() in the function body which will prevent happen the default behavior of the onClick event.
After adding the attribute type="button" in React solved my issue.

How to stop page reload on button click jquery

I am using this below code for button click event using jQuery. When button is clicked the page reloads.
$('#button1').click(function () {
//Code goes here
return false;
});
If your "button" is a button element, make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.
<button id="button1" type="button">Go</button>
If it's an input element, do so with jQuery with the following:
$('#button1').click(function(e){
e.preventDefault();
// Code goes here
});
Read more: event.preventDefault()
You can use event.preventDefault() to prevent the default event (click) from occurring.
$('#button1').click(function(e) {
// prevent click action
e.preventDefault();
// your code here
return false;
});

How to Prevent Users from Submitting a Form Twice

<input type="submit" name="btnADD" id="btnADD" value="ADD"/>
when user click add button twice, from get submitted twice with same data into table.
So Please help me to restrict user to submit from twice.
Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:
var $myForm = $("#my_form");
$myForm.submit(function(){
$myForm.submit(function(){
return false;
});
});
Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.
try out this code..
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />
You can disable the button after clicking or hide it.
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>
js :
function disableButton(button) {
button.disabled = true;
button.value = "submitting...."
button.form.submit();
}
If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.
http://www.xinotes.org/notes/note/369/
A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.
And if you are not using any framework and looking for simple workout.
You can take help of the
java.util.UUID.randomUUID();
Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.
For your help i am writing some code snippet to give idea about how to achieve the thing.
<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>
You could notify the user that he drinks too much coffee but the best is to disabled the button with javascript, for example like so:
$("#btnADD").on('click', function(btn) {
btn.disabled = true;
});
I made a solution based on rogueleaderr's answer:
jQuery('form').submit(function(){
jQuery(this).unbind('submit'); // unbind this submit handler first and ...
jQuery(this).submit(function(){ // added the new submit handler (that does nothing)
return false;
});
console.log('submitting form'); // only for testing purposes
});
My solution for a similar issue was to create a separate, hidden, submit button. It works like so:
You click the first, visible button.
The first button is disabled.
The onclick causes the second submit button to be pressed.
The form is submitted.
<input type="submit" value="Email" onclick="this.disabled=true; this.value='Emailing...'; document.getElementById('submit-button').click();">
<input type="submit" id='submit-button' value="Email" name="btnSubmitSendCertificate" style='display:none;'>
I went this route just for clarity for others working on the code. There are other solutions that may be subjectively better.
You can use JavaScript.
Attach form.submit.disabled = true; to the onsubmit event of the form.
A savvy user can circumvent it, but it should prevent 99% of users from submitting twice.
You can display successful message using a pop up with OK button when click OK redirect to somewhere else
Disable the Submit Button
$('#btnADD').attr('disabled','disabled');
or
$('#btnADD').attr('disabled','true');
When user click on submit button disable that button.
<form onSubmit="disable()"></form>
function disable()
{
document.getElementById('submitBtn').disabled = true;
//SUBMIT HERE
}
Create a class for the form, in my case I used: _submitlock
$(document).ready(function () {
$(document).on('submit', '._submitlock', function (event) {
// Check if the form has already been submitted
if (!$(this).hasClass('_submitted')) {
// Mark the form as submitted
$(this).addClass('_submitted');
// Update the attributes of the submit buttons
$(this).find('[type="submit"]').attr('disabled', 'disabled');
// Add classes required to visually change the state of the button
$(this).find('[type="submit"]').addClass("buttoninactive");
$(this).find('[type="submit"]').removeClass("buttonactive");
} else {
// Prevent the submit from occurring.
event.preventDefault();
}
});});
Put a class on all your buttons type="submit" like for example "button-disable-onsubmit" and use jQuery script like the following:
$(function(){
$(".button-disable-onsubmit").click(function(){
$(this).attr("disabled", "disabled");
$(this).closest("form").submit();
});
});
Remember to keep this code on a generic javascript file so you can use it in many pages. Like this, it becomes an elegant and easy-to-reuse solution.
Additionally you can even add another line to change the text value as well:
$(this).val("Sending, please wait.");
Add a class to the form when submitted, stopping a user double clicking/submitting
$('form[method=post]').each(function(){
$(this).submit(function(form_submission) {
if($(form_submission.target).attr('data-submitted')){
form_submission.preventDefault();
}else{
$(form_submission.target).attr('data-submitted', true);
}
});
});
You can add a class to your form and your submit button and use jquery:
$(function() {
// prevent the submit button to be pressed twice
$(".createForm").submit(function() {
$(this).find('.submit').attr('disabled', true);
$(this).find('.submit').text('Sending, please wait...');
});
})
None of these solutions worked for me as my form is a chat and repeated submits are also required. However I'm surprised this simple solution wasn't offered here which will work in all cases.
var sending = 0;
$('#myForm').submit(function(){
if (sending == 0){
sending++;
// SUBMIT FORM
}else{
return false;
}
setTimeout(function(){sending = 0;},1000); //RESET SENDING TO 0 AFTER ONE SECOND
}
This only allows one submit in any one second interval.

Categories

Resources