jQuery is triggering submit event when calling .submit() method - javascript

There are a ton of questions on SO asking why jQuery method 'submit()' is NOT triggering submit event.
I am asking the exact opposite:
Why is jQuery triggering submit event when calling submit method and how to get around this?
Here a simple JSFiddle showing the problem:
https://jsfiddle.net/vncu675x/
$(function () {
var i = 0;
$("form").find(":submit").text(Math.random());
$("form").submit(function (e) {
e.preventDefault();
if (confirm("Are you sure? " + i++)) {
$("form").submit();
}
});
});
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js"></script>
</head>
<body>
<form action="/">
<button type="submit">Submit</button>
</form>
</body>
</html>
I think it's a jQuery matter because pure JavaScript implementation is working as expected.

The line
$("form").submit();
is the same as $("form").trigger("submit") - ie it raises the submit event, which is the event that you're handling.
Instead, use the js native submit event by converting the jquery object to a DOM object:
$("form")[0].submit();
Even though they have the same name (submit) the two functions are for different types so have different actions.
Updated snippet:
$(function () {
var i = 0;
$("form").find(":submit").text(Math.random());
$("form").submit(function (e) {
e.preventDefault();
if (confirm("Are you sure? " + i++)) {
$("form")[0].submit();
}
});
});
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js"></script>
</head>
<body>
<form action="/">
<button type="submit">Submit</button>
</form>
</body>
</html>

Related

How to submit a form when a different button is clicked

I have a Save button which by default, submits a form. However, what I need to do is (in some circumstances, which are omitted for this question) instead open up a dialog when that Save button is clicked. Inside that dialog, the Yes button on will submit the form. The problem that I am wrestling with currently is applying the "submit" function of the form to the button.
form = document.getElementsByClassName('form_submit')[0];
formSubmitFunc = form.onSubmit;
// prevent the form from submitting normally, this will be done by the dialog
form.addEventListener('submit', function(event) {
event.preventDefault();
});
confirmDlgConfirmBtn.on('click', function() {
console.log('yes');
formSubmitFunc();
});
confirmDlgCancelBtn.on('click', function() {
console.log('no');
confirmDlg.hide();
})
saveButton.on('click', function() {
saveButton.disabled = false;
console.log('save');
confirmDlg.show();
});
Whenever I click on the confirmDlgConfirmBtn, instead of the form submitting as hoped for, I receive an error that reads as
Uncaught TypeError: o is not a function at ...
I have also tried setting formSubmitFunc = form.submit; amongst many others but cannot seem to get the default form submit function to execute when confirmDlgConfirmBtn is clicked. Any ideas?
I am mostly guessing here, but I think your problem lies in
// prevent the form from submitting normally, this will be done by the dialog
form.addEventListener('submit', function(event) {
event.preventDefault();
});
This should always prevent the form from being submitted, even when you are triggering it programmatically.
Instead, try to prevent the event default in the button click listener. I am also not completely sure about how you submit the form. Try submitting it directly with the submit() method
form = document.getElementsByClassName('form_submit')[0];
confirmDlgConfirmBtn.on('click', function() {
console.log('yes');
form.submit(); // using submit function
confirmDlg.hide(); // you probably also want to hide the dialog when the form is submitted
});
confirmDlgCancelBtn.on('click', function() {
console.log('no');
confirmDlg.hide();
})
saveButton.on('click', function(e) {
e.preventDefault(); // preventing the form submit here should work
saveButton.disabled = false;
console.log('save');
confirmDlg.show();
});
You should be able to do this with only HTML like:
<form id='myForm'>
...
</form>
<input type='submit' form='myForm'>
You can do it with jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Submit Form</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#saveBtn").click(function(){
$("#myForm").submit(); // Submit the form
});
});
</script>
</head>
<body>
<form action="/examples/html/action.php" method="post" id="myForm">
<label>First Name:</label>
<input type="text" name="first-name">
<button type="button" id="submitBtn">Submit Form</button>
</form>
<button type="button" id="saveBtn">Save</button>
</body>
</html>
Check the document for more guidance
Click Here

How to have one event prevent another event from firing on form submit in javascript?

I have an html page like this:
<html>
<head>
<script src="jquery.js"></script>
<script src="validation.js"></script>
<script>
function show_warning()
{
// If some condition is true, show a warning when the form is being submitted
if (condition)
{
alert("Warning");
}
}
$(document).ready(function() {
$("form").submit(show_warning);
});
</script>
</head>
<body>
<form method=POST>
...
</form>
</body>
</html>
And my validation.js looks like this:
$(document).ready(function() {
$("form").submit(function( event ) {
if (some_field_is_invalid)
{
alert("Error");
event.preventDefault();
return false;
}
});
});
I want my show_warning to only fire when the form passed validation, and is actually being submitted. Right now, even if validation fails, it still shows the warning.
What am I doing wrong?
If I am not mistaken (Its been a while I used jquery events handling), hope community will correct me.
TL;DR;
Remove this:
function show_warning()
{
// If some condition is true, show a warning when the form is being submitted
if (condition)
{
alert("Warning");
}
}
$(document).ready(function() {
$("form").submit(show_warning);
});
and update your validation.js like this:
// You can refactor the code to transform if to ternary
$(document).ready(function() {
$("form").submit(function( event ) {
if (some_field_is_invalid)
{
alert("Error");
event.preventDefault();
return false;
// Your special condition. Warning will show if form is valid and condition is true, if condition is not true but form is valid then it will submit without warning
} else if (condition) {
alert('Warning');
}
});
});
Explanation:
You are assigning 2 listeners in your code, one in your html and one in validation js, basically you have 2 functions listening to submit and both of them are independend from each other and being fired on submit of the form. But only validation.js is checking the validity of the form and show_warning is not checking the same validity, it has its own different condition (I dont know what condition is that). If you combine both of them in one listener function you will reach what you wanted.
P.S.
I would recommend you to use validation.js as a service so that it would provide you the function or a class that will return boolean based on the form validity and you would be able to use that method/class to first validate and then do what you need after its passed.
small example:
<html>
<head>
<script src="jquery.js"></script>
<!-- Lets say validation.js provides a function isFormValid(submitEvent): boolean -->
<!-- You can implement validation anyhow you want -->
<script src="validation.js"></script>
<script>
$(document).ready(function() {
$("form").submit(function(event) {
if (!isFormValid(event)) {
return event.preventDefault();
}
// Form is valid do what you need here
if (condition) {
alert('Warning');
}
});
});
</script>
</head>
</html>

$(window).load() is getting called infinite times

I've a simple approach for performing a click event on a button using js/jquery
<c:if test="${param.error eq true}">
<button id="btn-id" style="visibility = hidden;">Do Click Me</button>
<script type="text/javascript">
$(window).load(function() {
$("#btn-id").trigger("click");
});
</script>
</c:if>
with all this when I submit the form and error parameter comes true I get loop of calls on
$("#btn-id").trigger("click");
how can I restrict click to one time only?
Something like this?
<script type="text/javascript">
var buttonClicked = false;
$(window).load(function() {
if(!buttonClicked){
$("#btn-id").trigger("click");
buttonClicked = true;
}
});
</script>

How to call a JS function before a jquery button click(click through selector)

I want to call a JS function when a button is clicked and then continue execution of below jquery script
Form :
<form id="my_form">
<button type="button" id="Bshift" onclick="validation()">Clear</button>
</form>
Pure JS Function:
function validation(){
// this has to be executed first
// do something here..
}
Jquery:
$(document).ready(function(){
$('#Bshift').submit(function(){
// this has to be executed second
// do something here.
}
});
I would like to know is how I execute my function before my jquery submit.
HTML:
<form id="my_form">
<button type="button" id="Bshift">Clear</button>
</form>
JS:
$(document).ready(function(){
$('#Bshift').on('click', function(){ // I think this should be click event because you're not submitting your page you're just clearing it based on "CLEAR"
validation();
}
function validation(){
do something here..
}
}
Note: Your function must be outside the event triggers.
Call your validation function inside submit call.
$(document).ready(function(){
$('#Bshift').submit(function(){
validation()
do something here.
}
}
HTML Code
<button type="button" id="Bshift" >Clear</button>
You have one more option to submit the form through ajax after validation.
$('my_form').on('submit', function(e) {
e.preventDefault();
if (validation()){
$.ajax({...});
}
});
Invoke validation function on form submit event
$(document).ready(function(){
validation(); // function call
$('#my_form').submit(function(){ //form submit event
// do something here.
}
});
function validation(){
// do something here..
}
Edited code, please test my code.
<script>
function validation(){
alert('How are you?');
}
$(document).ready(function(){
$('#Bshift').click(function(){
validation();
alert('Fine and you?');
});
});
</script>
<form id="my_form">
<button type="button" id="Bshift">Clear</button>
</form>
Demo

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources