I have a form which is made like this:
<form id= 'lol' name = 'whyyyyy'>
<input name='dumbo'>
<input name='idiot'>
<input type='submit' value='I have no idea why its like this' onclick='document.lol.submit()'>
</form>
Now, I want to prevent the actual sending of the form, but so far all attempts failed.
My current code looks like this:
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
})
but the inline submit command bypasses as it seems the jQuery function.
Can someone shred light into it?
EDIT:
The form CANNOT be changed, I don't have permission to change.
the on click code should trigger the submit function, it some complex validation wall of code in it. So I have to cache the submit action that it triggers, but I can't do that at moment.
the submit function should be triggered on send but it does not get triggered.
Here is an example of the code in jfiddle. As you can see it gets past by jQuery...
http://jsfiddle.net/StCPp/4/
if you don't need a submit button, why don't you use a regular button instead
<input type="button" />
<input type='button' value='i have no idea why he done it like this' onclick='document.getElementById('lol').submit()'>
Just use a normal button instead of a submit.
If you want to bypass a submit button you can make the class of the button cancel.
<input type='submit' class='cancel' value='i have no idea why he done it like this' onclick='document.lol.submit()'>
In your add-on JavaScript, remove the inline onclick event and replace it with whatever you desire. Problem solved.
You could also completely remove his button and replace it with one of your choice.
Remove the document.lol.submit function. This way, you can do whatever you want.
// Magic line
delete document.lol.submit;
// Or
$('form[name="whyyyyy"] input[type=submit]').attr('onclick', '');
$(document).ready(function(){
$('form[name="whyyyyy"]').submit(function(e){
e.preventDefault();
alert(1);
return false;
});
});
Ok so if I got this right you could remove the inline event handler onclick and add your custom handler (where you do the validation and all necessary steps):
$(document).ready(function() {
var $submit_button = $('input[type=submit]');
$submit_button.removeAttr('onclick');
$submit_button.click(function() {
//TODO: implement your custom handler
//execute validation etc.
});
});
Remove the onclick
$('input[type=submit]').attr('onclick','')
Then add the click event to function ready
$('input[type=submit]').on('click',function(){
//do your event
});
You aren't necessarily required to use jquery to implement this. You could use standard javascript.
$(document).ready(function(){
document.whyyyyy.submit = function(e){
alert(1);
return false;
};
});
This example works, but you might be hitting a jquery bug.
Related
I'm in trouble when I use form submit event in jQuery.
Markups
<form>
<input type="text" name="username" />
<a id="btn_submit">Submit</a>
<input type="submit" />
</form>
Event listener
function valid() { return false; }
$('form').submit(function() {
if(!valid()) {
return false;
}
});
Then, when I click that <input type="submit" /> it do trigger that event, and can cancel the submit event.
But when I trigger the form submit on the .btn_submit tag, return false cannot cancel the submit.
Failure of cancel
$('#btn_submit').click(function() {
$('form').submit();
// $('form').trigger('submit');
// document.forms[0].submit();
});
So, now the question is, if I must use an a.btn_submit to trigger the submit of form, and I want to cancel that submit in case.
How should I trigger?
How should I cancel?
Please help!
I made a fiddle http://jsfiddle.net/69wcduv5/2/.
But it seemed cannot submit in jsfiddle.
My final solution (a bit dirty)
I can create a submit input inside the form, then trigger a click on it. Then remove it.
If I trigger the submit in this way, I acts exactly the same as I expected:
The validation code inside the $('form').submit(function() {}); don't have to change.
If the form has something like <input type="text" required />, it can do well.
I can style well on that anchor. Not the f**king <input type="submit" />
Thank you all for your patient, best regards.
And hoping for a clean better solution.
$("a.btn_submit").click(function(){
if($('form').valid())
{
$('form').submit();
}
});
$('form').submit(function(event) {
if(!valid()) {
event.preventDefault();
}
});
Seems weird to use a link to submit a form, but your problem is you are not cancelling the click action on the anchor.
$('.btn_submit').on("click", function(evt) {
evt.preventDefault();
$('form').submit();
});
I understand now what you are trying to achieve, so please ignore what I wrote before.
formElement.submit() and its jQuery equivalent very deliberately do not trigger an onsumbit event. Othwise there is the potential for infinite recursion.
Therefore, you cannot execute $('form').submit(); and hope for an onsubmit handler to intercept.
Your best bet is probably your "dirty" idea. Namely to trigger a click on a (hidden) type="submit" button.
Call the submit in this way, the most close to my intention:
$.fn.natural_submit = function() {
if($(this).is('form')) {
var $form = $(this);
var $input_submit = $('<input type="submit" />').hide().appendTo($form);
$input_submit.trigger('click');
$input_submit.remove();
}
}
$('#btn_submit').click(function() {
$('form').natural_submit();
});
I have a problem. I want to make server do something after clicking on button.
This is my HTML code:
<input name="like" id="like" value="Like" type="submit" />
<script>
$('like').click(function(){
$.post('/test')
});
</script>
and this is my server-side code:
app.post('/test', function (req, res) {
console.log('works');
});
And it doesn't work.
Your problem is here, you have forgotten the # for targeting element by id, so click would never be invoke.
$('#like').click(function(){
$.post('/test');
});
It looks like you aren't selecting the input tag correctly. If you want to select a DOM element by ID, you'll want to use '#IDname' as your selector.
For this example, that means changing it to
...
$('#like').click(function(){
...
This also might not fix the error entirely: using a an input field with a type of "submit", you will likely have to do something like this:
...
$('#like').click(function(e){
e.preventDefault();
...
to keep the default submit event on the input from "bubbling up."
<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.
I have code in the below format in my JSP.
sumbit
On pressing the link my form gets submitted. However, I need to block the default a href behaviour and just need to call the submit function.The submit function submits the form
I have tried catching the click event on a HREF by jQuery and then firing e.preventDefault(). Following the same, I have picked up the HREF attribute, and then done an eval() to fire the function.
However, I have not been able to stop the default HREF functionality, and a new page is always saved in browser cache.
I also don't have the freedom to manually go in and change the code. Please suggest.
UPDATE
The issue with the code is:
submit
is one of the example of HREF being used in JSP. There may be different type of functions being called, using the above format:
I had used the below jQuery:
$("a[href^=\'javascript\']").live('click',function(e)
{
e.preventdefault();
eval($(this).attr('href'));
return false;
});
However, this does not stop the default HREF functionality. What am I missing?
As you mentioned in your question, you cannot manually change the markup.
So, I think, this is what you really want.
<form id='myform' action=''>
</form>
submit
JS:
function submit() {
document.getElementById('myform').submit();
}
jQuery(function() {
$('a').click(function() {
var href = $(this).attr('href').replace('javascript:','');
console.log(href);
alert('hi');
eval(href);
return false;
});
});
Demo
Update:
You can avoid eval(href), by using window[href]();
See this Demo
Try:
sumbit
Probably a simple noob error but I cannot figure it out. I have a submit button and after the user clicks it I want it to disappear and be replaced with "Thanks for submitting your info".
Here's what I have:
<script>
$(document).ready(function() {
$('#emailsubmit').onClick(function() {
$(this).replaceWith('<p>Thanks for signing up!</p>');
)};
)};
</script>
<input id="emailsubmit" name="submit" type="submit" value="Send " />
Looks ok to me, but on click, nothing happens. Any advice would be greatly appreciated.
The name of the function is click, not onClick, and you have a couple of syntax errors to boot.
$(document).ready(function() {
$('#emailsubmit').click(function() {
$(this).replaceWith('<p>Thanks for signing up!</p>');
});
});
You best use click instead of onClick
You're confusing inline, DOM-zero events (onClick) with jQuery's alias event methods.
jQuery has a click method (short for on('click...) but no onClick() method. This would throw an error, meaning you should always consult your browser console before anything else.
$('#emailsubmit').on('click', function() {...
The method is named click not onClick.
Also, removing the submit button will keep the form from being posted. Hide it instead:
$(this).hide().after('<p>Thanks for signing up!</p>');