I have the following form on a page:
<form action="/" method="post">
<select id="SelectedMonth" name="SelectedMonth">
<option>7/1/2017</option>
<option>6/1/2017</option>
</select>
</form>
I am trying to use the following jquery snippet to submit the form. The jquery code resides outside of the form and the form is the only form on the page.
$("#SelectedMonth").change(function () {
alert(this.value);
$('form').submit(function (event) {
alert("Submitted");
event.preventDefault();
});
});
The first alert is triggered and shows the selected value but the submit is never triggered.
It seems like this is pretty straight forward but it is not working. What am I missing?
TIA
change action and make it blank
and change function like this
$("#SelectedMonth").change(function () {
$('form').submit();
});
and it will work
That's because, while you can change the selected element in the drop down (thus causing the first alert() to fire), you have no mechanism for submitting the form, so the second one doesn't.
You need to add a submit button so that the submit event of the form can be triggered.
Also, the way you have the code, the submit event handler won't actually fire unless you change your selection in the drop down first. You probably don't want that behavior. The two event handlers should be set up independent of each other.
$("#SelectedMonth").change(function () {
alert(this.value);
});
$('form').submit(function (event) {
alert("Submitted");
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/" method="post">
<select id="SelectedMonth" name="SelectedMonth">
<option>7/1/2017</option>
<option>6/1/2017</option>
</select>
<button type="submit">Submit</button>
</form>
you are putting the submit event inside change event try and also add a submit button to submit the event
$("#SelectedMonth").change(function () {
alert(this.value);
});
$('form').submit(function (event) {
event.preventDefault();
alert("Submitted");
});
if you want to submit on date chaneg then try this
$("#SelectedMonth").change(function () {
$('form').trigger('submit');
});
$('form').submit(function (event) {
event.preventDefault();
alert("Submitted");
});
The answer to the question "why it does not work" is that .submit(function(){}) not actually submits form but add submit handler - function that will be executed when form will be submitted
This method is a shortcut for .on( "submit", handler ) in the first variation, and .trigger( "submit" ) in the third.
Description: Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.
So if you pass function to it, it will BIND handler. When you will trigger it without params, it will actually submits form.
You dont need button to submit form.
So actually code must be something like this
$('form').submit(function (event) {
alert("Submitted");
event.preventDefault();
});
$("#SelectedMonth").change(function () {
$('form').submit();
});
Related
I'm trying to submit a form to Campaign Monitor. They offer this code example to POST via Ajax.
This is my code for my multi-step modal.
var next_step = false;
var final_step = false;
$('.next').on('click', function(e){
e.preventDefault();
if (next_step) {
$('#step-1').slideUp(function(){
$('#step-2').slideDown();
$('.next').html('Submit');// Change button text to submit
final_step = true;
});
}
next_step = true;
if (final_step) {
$('#myform').submit(function (e){
alert('submit started'); //This never fires unless I remove the preventDefault();
e.preventDefault();//But if I remove this, the page will refresh
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert('error');
} else {
alert('success');
}
})
});
}
});
On the last step of the form, I check whether final_step is true, if so, go ahead and submit the form via ajax.
The problem is that it just doesn't do anything? But if I remove the e.preventDefault(); from the $('#myform') it will post the form as normal and re-direct you to the form URL.
How can I fix this?
What you are doing currently is wiring up an onsubmit handler. Not invoking submit.
$('#myform').submit(function (e){ });
...is the same thing as...
<form action="#" method="post" onsubmit="return someFunction()">
... which is the same as ...
$('#myForm').on('submit', function(e){});
You are never submitting the form.
What you are looking for is to use Ajax to post the data to the server and not submit the form.
You can do that like this:
$.ajax({
type: "POST",
url: "SomeUrl.aspx",
data: dataString,
success: function() {
//display message back to user here
}
});
dataString would be replaced with the values you posting.
$('#myform').submit(function (e){
just registers an event handler and attaches it to the "submit" event of "myform", it doesn't actually cause a submit. It means you're saying you'd like this function to be run every time the form is submitted. This handler function should be outside your $('.next').on('click', function(e){ block. Just below it will do.
If, within the $('.next').on('click', function(e){ block you wish to cause the form to be submitted, write:
$('#myform').submit();
This will actually trigger the form submission.
See https://api.jquery.com/submit/ for more info on what the different method signatures of "submit" actually do.
This line: $('#myform').submit(function (e) { registers the function you pass as an argument as a handler to the submit event of the form, and does not invoke a submit action. I'm not sure whether or not this is the problem, though I would recommend preventDefault() outside of the wizard flow
(e.g.
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
}
});
)
Then inside the if(final_step) just do the post without worrying about the form.
Also, you'd do good in not setting a submit button inside the form if you do not wish to use it's functionality. Just create an element with a click event that sends the data rather than registering to the submit event of the form.
I'm not sure but I always do $('#form').submit() after click in element and catch this event (e.g. by $('#form').on('submit', function () { .. });) in other place.
Lets say I have this form
<form onsubmit="submitData();">
<input type="text" pattern="^[A-z]+$" required>
<button type="submit">OK</button>
</form>
Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern).
If I switch the value of onsubmit on the form to "return false;" then it won't navigate but "submitData(); return false;" doesn't work. Any other ideas?
Try adding e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) {, like this:
function submitData(e) {
e.preventDefault();
...
}
See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Just add event.preventDefault that is automatically pass by the form to the function:
function submitData(event){
event.preventDefault();
//your code will be here
}
read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Use event.preventDefault().
Learn more: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
add this to your code:
document.getElementById("addYourTagHERE").addEventListener("onsubmit", function(event){
event.preventDefault()
});
or this in your function:
function submitData(event) {
event.preventDefault();
}
You'd want to cancel the default action of the submit event handler, so:
function submitData() {
// whatever logic you have...
return false;
}
I believe this works too:
function submitData( e ) {
e.preventDefault();
// whatever logic you have...
}
I have multiple forms on the same page with the class form_delete.
How do I iterate over those forms in jQuery adding a submit event that will uniquely apply to each form?
I've tried this using $('.form_delete').each(...); but when I add $(this).submit(...) events it's not working (event does not register).
Forms:
<form class="form_delete">
</form>
<form class="form_delete">
</form>
<form class="form_delete">keep adding n forms to infinity ;)
jQuery:
$('.form_delete').each(function() {
$(this).submit( function(event) {
// Nothing gets registered here
});
}
$('.form_delete').each(function() {
$(this).on("submit", function(e) { // submit button pressed
// prevent form from doing what it normally does when submit button is pressed
e.preventDefault();
// do anything else that you want to do when the submit button is pressed
alert( "Hi");
});
});
jQuery's event delegation is also an option.
$('body').on('submit', '.form_delete', function submitCB(e) {
e.preventDefault();
});
When the event bubbles up to the body then jQuery will check the target element against the string selector (parm 2), and only call the callback (parm3) if it matches.
This way you only have on event listener on the page, as opposed to many.
I don't know why you use .each(); anyway if all forms with same class just use
$('.form_delete').on('submit',function(e){
e.preventDefault();
alert($(this).index());
return false;
});
in that case you will need something like data-selectForm to define which form you submited
<form class="form_delete" data-selectForm="firstform">
</form>
<form class="form_delete" data-selectForm="secondform">
</form>
and then use
$('.form_delete').on('submit',function(e){
e.preventDefault();
alert($(this).data('selectForm'));
return false;
});
I have an Input element that submits a form:
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
I need the button to call a javascript function, and then post the form normally.
How would that be done in jQuery?
$('#downloadButton').on('click', function (e) {
e.preventDefault();
//call your function here
$(this).parents('form').submit();
});
the preventDefault() call is important because it stops the submission of the form so you can call your function before the form submit is called at the end.
You can do:
<form onsubmit="return doSomething();">
</form>
function doSomething() {
// do something
return true;
}
If in the doSomething function you don't like what you're seeing, then return false instead of true.
EDIT
The jQuery equivalent (to satisfy both commenters): remove the onsubmit from the HTML and replace with:
jQuery(document).ready(function () {
jQuery("form#myFormId").submit(doSomething);
});
Take a look at this jsfiddle
It changes the case of textbox content to to upper case before submitting the form
$('#formID').on('submit', function () {
//var form = $(this),
//input = form.find('input[type="text"]');
//input.val(input.val().toUpperCase());
//alert(input.val());
// call your function here!
});
this is what you request:
1.- click a button (adding event handler)
2.- call a function
3.- submit form
myfunction(){
//do wathever you want
$('#formid').submit();
}
$(document).on("click", "#downloadButton", myfunction);
you can do also:
$(document).on("click", "#downloadButton", function(event){
$('#formid').submit();
});
without having an extra function
but the solution of #Paritosh is the more accurate.
jsFiddle here
Change input type to type="button" and use:
$('#downloadButton').click(function() {
//Do any javascript stuff here
//And here, etc. Then, when ready...
$('#yourFormID').submit();
});
I recommend assigning an ID attribute to your form as it is good practice.
<form id="yourFormID" action="" method="POST">
Perhaps you have only one form on this page, in that case $('form').submit() is fine. But in future (or perhaps even on this page, you haven't said) you may have multiple forms on a page and therefore the ID is necessary to specify the exact form to be submitted.
Note that if you do NOT change the submit button element's <input type="submit" to <input type="button", then you must use e.preventDefault() to prevent the button's default action. Why bother with that? Just change type="button" and use less code and less future confusion.
add a submit event on form.
$('form').submit(function(event){
event.preventDefault();
var formObj = $(this);
var formData = formObj.serialize();
$.ajax({
type: 'post',
data: formData
}).done(function(response){
console.info(response);
// update UI here accordingly.
});
});
We have a script that tracks form submits by adding an event listener to the form. The problem is that one customer submits the form via a link using
Submit
which ignores the event listener. Here's a JSFiddle to demonstrate: http://jsfiddle.net/XhLkG/
As you can see the Submit button triggers the alert while the Submit link simply just submits the form and bypasses the event listener.
Is there a way to still trigger the event listener?
EDIT: We cannot change the markup since it's on our customer's homepage where they have embedded our script. Sorry if I didn't make it clear.
You can use this:
var form = document.getElementsByClassName('form');
form[0].addEventListener("submit", function(e) {
e.preventDefault();
alert('event');
});
form[0].childNodes[3].addEventListener("click", function(e) {
e.preventDefault();
alert('event');
});
instead of using the href try this
<form method="post" name="formname" class="form">
<input type="text" name="hello">
<a onclick="javascript:document.formname.submit();">Submit</a>
<input type="submit">
</form>
remove the href and replace it with onclick
try the following with jquery:
$("form").submit(function (e) {
e.preventDefault();
alert('event');
});
Reference here.