jQuery event preventdefault and continue - javascript

I am currently working on a Django project and am using the Django admin and its jQuery to add a modal between the submit button and the real form submit.
To achieve this I've implemented the following:
var submit_form;
django.jQuery('form').submit(function (event) {
event.preventDefault();
submit_form = this;
modal.open();
});
and in modal close function I'm using:
submit_form.submit();
This actually works, but I loose the Django admin functionality of the "Save and add another" and "Save and continue editing" buttons.
They all do now the same action as the default submit button.
The only thing added to the two other submit buttons is a name attribute:
<input type="submit" value="Save" class="default" name="_save">
<input type="submit" value="Save and add another" name="_addanother">
<input type="submit" value="Save and continue editing" name="_continue">
I did also check into event and used event.currentTarget.submit(); in modal close function, but this did not actually work either.
Does someone have an idea how to properly prevent default submit and execute it later?
Thanks.

Okay, I figured out how to do this. I had to add a hidden input to my form including the name from the submit button.
The following is the modified function I use to fill the missing input:
django.jQuery('form').submit(function (event) {
event.preventDefault();
submit_form = this;
// Append action as hidden input
var action = django.jQuery(this).find('input[type=submit]:focus').attr('name');
var input = django.jQuery('<input>', {
type: 'hidden',
name: action
});
submit_form.append(input[0]);
// Release save button
django.jQuery(':submit').blur();
// Finally open modal window
modal.open();
});

Related

make a button behave like a submit button in a form

I try to make a confirm popup that going to jump when user click on a button of form.
If the user click on ok in the popup, the form goting to submit.
Its must to be dynamic becuse i have a lot of forms in one page and all form must to get the confirm popup.
I replaced the submit button with a normal button and when the user click on the button the confirm jumping.
<input type='button' name='submitButton' onclick="openPopup(this);">
Its work amazing but when the user into a text input and press on eneter its not submit the form.
What can i do?
Use following JS:
<input type='submit' name='submitButton' onclick="openPopup(this);">
If you can't use a submit button in your form you just need to handle this in the keydown event in your form inputs to check if Enter key is pressed and click your button dynamically:
$("#formID").find('input[type=text]').on('keydown', function (e) {
if (e.keyCode == 13) {
$('[name="submitButton"]').click();
}
});
Note:
I used formID as id of your form you just need to replace it with your form id.
$(document).ready(function() {
$('input').keypress(function(data) {
if (data.keyCode == 13)
data.target.form.submitButton.click();
});
});
When you accept confirmation then fire this event
$('[name="submitButton"]').click();

Confirm form submit with two buttons in BootboxJS

I'm using Bootbox.js to show a confirmation box prior to submitting a form. The form has two submit buttons that handle two different actions. I was successful in showing the dialog and submitting the form, however the value of the button that was clicked is not included in the request. This is obvious, because by submitting the form manually no buttons were clicked. As I need to have a working form with and without javascript, I can't use hidden fields with a value changed at runtime by javascript. I then tried triggering the click event on the button itself when I leave the popup dialog, however I don't know how I could understand which button was originally clicked. Also, the click will probably trigger another submit event causing an infinite loop. How can I prevent that?
<form name="myform" action="myaction" method="post">
...
<button type="submit" name="decline" value="decline">Decline</button>
<button type="submit" name="accept" value="accept">Accept</button>
</form>
$(document).ready(function() {
$('form[name="myform"]').submit(function(e) {
bootbox.confirm({
message: '...',
callback: function(result) {
if (result) {
$('button[name="accept"]').click();
}
}
});
e.preventDefault();
}
});
An (admittedly brute-force) method of making your current script work is to create a sentinel variable that you toggle on the submission of your form:
$(function() {
var firstClick = true;
$('form[name="myform"]').submit(function(e) {
if(firstClick === true){
firstClick = false;
bootbox.confirm({
message: '...',
callback: function(result) {
if (result) {
$('button[name="accept"]').click();
}
}
});
e.preventDefault();
}
}
});
This lets you handle the form submission the first time the submit event is triggered, with subsequent submit events being allowed to submit the page.
It's also worth nothing (per the HTML spec) that
A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.
So your two buttons (Accept and Decline) could share the same name attribute, with only the button that was clicked reporting it's value.

window.onbeforeunload allow submit button?

I have the following javascript to show a confirm box when a user leaves the page.
My problem is, it is showing even when user clicks the submit button inside a form in my page. I don't want this to be triggered on form submit and on a span click.
How can I allow form submit and span click in the function below?
window.onbeforeunload = function (e) {
e = e || window.event;
return '';
};
EDIT-------------------------------
sorry, it is now a form, it is simple button and a href:
I have one page that uses only a button:
<input type="button" value="Save" id="btn-crop" />
and a link:
<a href="done.php" class=button2>Save</a>
You could call [Event].stopPropagation in an callback of submit event for each button in the page.
This function would stop the callback function of the beforeunload event when would go submit the button.
You can read more about the [Event].stopPropagation
here.
Like so: Button.addEventListener("submit",function(Event){Event.stopPropagation()})
You should be able to check what object dispatched the event using e.currentTarget property and then show the prompt if necessary.

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.

Submitting a form with the enter button in a form with several submit buttons

I have a form with a simple text field and multiple submit buttons. When the user presses enter, I want to submit the form with a specific submit button, but it looks like the form just chooses the first button instead. Is there any way to tell the browser which submit button to choose when user presses enter? Preferrably without javascript, but I'll take it if that's the only solution.
Edit: I have no other choice than having multiple submit buttons. This is a legacy app.
There's no way. The simplest solution is just to ensure that the first submit button in the form is the one you want triggered by the Enter button.
Note that this submit button can be a duplicate of a button elsewhere in the form, and it doesn't have to be visible.
You can use simple JS to catch the onkeypress event:
onkeypress="if ((event.keyCode | event.which) == 13) { document.getElementById('MySubmitButton').click(); return false; }"
Just add this to the textbox tag and replace "MySubmitButton" with the ID of the desired submit button.
Note: use ID, not name.
If you had the following HTML
<form id="form_one">
<input type="submit" value="Submit 1" />
</form>
<form id="form_two">
<input type="submit" value="Submit 2" />
</form>
Then you could have a bit of jQuery as follows
$(document).ready(function() {
$(this).keydown(function(e) {
if (e.keyCode == '13') {
$("#form_one").submit();
}
});
});
Obviously you'd have to put in the logic to decide which form to submit.
Also as far as I know if a control in "form_one" had focus and you hit enter it would automatically submit that form the control is contained within.
you can just define a javascript method on the "onclick" or "onkeypress" event of the button, from which u wanted to get the form submitted. But u have to define the process to occur in the javascript function

Categories

Resources