Submit a form and stay on the same page? - javascript

I'm trying to make my form stay on the same page using jquery. I'm using a form named #clientUpdate-form that posts it's input to update.php. I have tried removing the window.location.href and tried changing it to window.location.href="edit_form.php?edit_id="+edit_id but the form always reverts back to index.php
Full Code:
/* Update Record */
$(document).on('submit', '#clientUpdate-form', function() {
$.post("update.php", $(this).serialize()).done(function(data) {
$("#dis").fadeOut();
$("#dis").fadeIn('slow', function() {
$("#dis").html('<div class="alert alert-info">' + data + '</div>');
$("#clientUpdate-form")[0].reset();
$("body").fadeOut('slow', function() {
$("body").fadeOut('slow');
window.location.href = "index.php";
});
});
});
return false;
});
/* Update Record */

you need to prevent the default event of form submit.
$(document).on('submit', '#clientUpdate-form', function(e) { // note the e, thats the event
e.preventDefault(); // this stops the default event of the form
// then your stuff goes here
});

Related

Adding Google Analytics event to form submit

I'm looking to add a Google Analytics event to a form that I can not access the inline html, so I can not add it as a onClick="" event straight to the html.
So my solution has been so far:
$(function() {
$(".form_submit input").on("click", function() {
dataLayer.push({
"event": "Kontakt",
"eventCategory": "Submit",
"eventAction": "Kirjuta meile",
"eventLabel": "Kirjuta meile"
});
});
});
Althought this does not seem to work as clicking the submit button possibly stops all functions and refreshes the page.
How can I run the function before submit and then submit the form after? I've been suggested using preventDefault(); and the after calling the submit again with $('form').one('submit', ... but have been unable to implement this due to lack of skill.
View site: http://avrame.com/en (the form is at the bottom of the page)
Any suggestions appreciated.
You can actually push functions to dataLayer, and it will be executed after the first event.
I would do
delegate the submit watch event to document level (see Jquery .on() submit event)
intercept the first submit, pushing event and preventing default behavior
and insert a function inside dataLayer, which submits the form again, but this time it won't be halted
The code:
window.submitGA = false;
$(function() {
$(document).on('submit','.form_submit',function(event){
if (!window.submitGA)
{
window.submitGA = true;
dataLayer.push({
"event": "Kontakt",
"eventCategory": "Submit",
"eventAction": "Kirjuta meile",
"eventLabel": "Kirjuta meile"
});
dataLayer.push(function(){
$('.form_submit').submit();
});
event.preventDefault();
}
});
});
Working solution ended up using this callback method:
var form = document.getElementsByClassName('.footer__contact form');
form.addEventListener('submit', function(event) {
event.preventDefault();
setTimeout(submitForm, 1000);
var formSubmitted = false;
function submitForm() {
if (!formSubmitted) {
formSubmitted = true;
form.submit();
}
}
ga('send', 'event', 'submit', 'Saada', 'Kirjuta meile', {
hitCallback: submitForm
});
});
Reference from: https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#hitcallback

Appended li disappears after submit form

I am making a todo list using jquery. I have problem when submit the form the appended li appears and disappears immediately. Can anyone help me Please?
Here's my Jquery code so far:
$(function(){
$('input:checkbox').click(function(){
if ($(this).is(':checked')) {
$(this).parent().addClass('completed');
}
else {
$(this).parent().removeClass('completed');
}
});
$('#clearComp').click(function(){
$('.completed').fadeOut();
});
$('#todo_from').submit( function(e) {
e.preventDefault();
return false;
});
});
function addTodo(){
var itemToAdd = $('#txtBox').val();
if ( itemToAdd ) {
$('#todoList').append('<li class="todoBlk"><input type="checkbox" class"checkbox">'+itemToAdd+'</li>');
}
$('#txtBox').val('').focus();
}
JS Bin
That is because upon pressing the Enter key, the form is submitting itself and forcing the page to refresh. So you should use .preventDefault() from preventing this from happening:
$('form').on('submit', function(e) {
var itemToAdd = $('#txtBox').val();
if ( itemToAdd ) {
$('#todoList').append('<li class="todoBlk"><input type="checkbox" class"checkbox">'+itemToAdd+'</li>');
}
$('#txtBox').val('').focus();
e.preventDefault();
});
This code also allows you to remove the inline JS for the onsubmit attribute.
Update: I also noticed a problem with your example is that your button fails to clear checked items that are dynamically added. This is because when jQuery is first executed on the page, the click listener is only bound to pre-existing elements. Do consider using .on() to bind the click event to dynamically added list items. Here's the fixed version: http://jsbin.com/hiyuqikura/1/edit?html,js,output
$(function(){
// On submit, prevent default form action and add item if input is not empty
$('form').on('submit', function(e) {
var itemToAdd = $('#txtBox').val();
if ( itemToAdd ) {
$('#todoList').append('<li class="todoBlk"><input type="checkbox" class="checkbox">'+itemToAdd+'</li>');
}
$('#txtBox').val('').focus();
e.preventDefault();
});
// Listen to click event on dynamically added elements
$(document).on('click', 'input.checkbox', function(){
if ($(this).is(':checked')) {
$(this).parent().addClass('completed');
}
else {
$(this).parent().removeClass('completed');
}
});
$('#clearComp').click(function(){
$('.completed').fadeOut();
});
});
comment out the $('#todo_from').submit() function and change the form tag to this
<form id="todo_form" onsubmit="addTodo(); return false;">
You've got the wrong id here $('#todo_from').submit. Should be #todo_form

jQuery submit method doesnt submit form data

I am using jQuery to prevent submitting form on clicking if amount is <10 and using jQuery AJAX to update amount after every 2 seconds. If meanwhile amount > 10 then I want to re-submit the form which is already filled.
I have used
$("form").submit(function(e){ e.Preventdefault;})
To prevent submitting the form when amount < 10 and if meanwhile amount updates to > 10 then I am unbinding the submit button and calling submit function again.
$("form").unbind("submit");
$("form").submit();
But this doesnt POST the data to action URL.
Here's my complete code
$(document).ready(function() {
var damount;
var checking=0;
setInterval(Call2, 3000);
function Call2() {
damount=$("#damount").val();
if(damount>10 && checking==1)
{
$("form").unbind('submit');
$("form").submit();
}
}
$("#addproject").click(function(){
checking=1;
damount=$("#damount").val();
if(damount<10)
{
$("form").submit(function(e){
e.preventDefault();
});
}
});
See another similar post and my response here:
https://stackoverflow.com/a/25806502/4021932
You're trying to call submit() on a jQuery object, which won't work. You need to call it on the DOM element.
$("form").unbind('submit'); //This is fine as it's dealing with the submit event, which jQuery handles
$("form")[0].submit(); //This calls submit() on the form DOM element
What about trying something like this:
$(function () {
$("form").submit(function (e) {
var damount = parseInt($("#damount").val());
if (damount < 10) {
e.preventDefault();
}
});
setInterval(function () {
$("form")[0].submit();
}, 3000);
});

Prevent bootstrap-3 modal from closing when the form has changes

I'm trying to prevent the bootstrap-3 modal from closing without warning when there are changes made to the form inside the modal. However when I listen to the events fired by the modal and return false it will prevent the modal from closing ever. Here's my code:
$(function() {
$('body').live('shown.bs.modal', '#quickbutton-create', function () {
$(this).find('#quickbutton-create form').monitor();
});
$('body').live('hide.bs.modal', '#quickbutton-create', function () {
if ($(this).find('#quickbutton-create form').monitor('has_changed')) {
if (!confirm('Are you sure?')) {
return false;
}
}
});
});
So in short, in this case; how do I prevent the modal from closing just this once.
Ok so I figured it out, instead of return false I needed to event.preventDefault()
jsfiddle here: http://jsfiddle.net/ACYBv/1/
$(function() {
$('.modal').on('shown.bs.modal, loaded.bs.modal', function(e) {
// set form state
$(this).data('form-data', $(this).find('form').serialize());
});
$('.modal').on('hide.bs.modal', function(e) {
// check if the form data was changed since the modal was openened
if($(this).data('form-data') != $(this).find('form').serialize()) {
if(!confirm('you sure??')) {
e.preventDefault();
}
}
});
});

How can I unobtrusively disable submit buttons with Javascript and Prototype?

So I found this recommendation, but I can't quite seem to figure out how.
This is the code I originally started with:
function greySubmits(e) {
var value = e.srcElement.defaultValue;
// This doesn't work, but it needs to
$(e).insert('<input type="hidden" name="commit" value="' + value + '" />');
// This causes IE to not submit at all
$$("input[type='submit']").each(function(v) {v.disabled = true;})
}
// This works fine
Event.observe(window, 'load', function() {
$$("input[type='submit']").each(function(e) {
Event.observe(e, 'click', greySubmits);
});
});
Anyway, I am pretty close, but I can't seem to get any further.
Thanks for any help at all!
Update: Sorry, I guess I wasn't entirely clear. I'd like to disable all of the submit buttons when someone clicks a submit button. But I do need to send along the value of the submit button so the server knows which button I clicked, hence the insert call. (Note: insert does not create a child of the element you call it on.) And then after disabling the submit buttons I need to call the containing form of the submit buttons submit call, as IE will not submit after you disable the button. Does that make sense?
You need to do exactly what the answer says :
"Do not disable the button in its "onclick", but save it, and do it in form's onsubmit."
So in greySubmits() keep the line that sets the hidden value, but remove the line that disables all the submit buttons.
Then add another event handler in your online - to the form, not the submit buttons - that does the disabling.
function reallyGreySubmits(e) {
// This causes IE to not submit at all
$$("input[type='submit']").each(function(v) {v.disabled = true;})
}
Event.observe(window, 'load', function() {
$$("input[type='submit']").each(function(e) {
Event.observe(e, 'click', greySubmits);
});
$$("form").each(function(e) {
Event.observe(e, 'submit', reallyGreySubmits);
});
});
Another option, which I've used is to not disable the submits but to swap visibility between two elements. On click, mark the submits hidden, and then make visible a div or some other element that displays as "disabled" in their place.
I finally got it to work. Ryan helped so I'll upvote him :-) Here's the code:
function replaceSubmit(e) {
var el = e.element();
Element.insert(el, { 'before': '<input type="hidden" name="' + el.name + '" value="' + el.value +'" />'});
}
function greySubmits(e) {
// Don't disable the submit if the submit was stopped with a return(false)
if (e.returnValue) {
$$("input[type='submit']").each(function(v) {v.disabled = true;})
}
}
function fixButtons() {
$$("input[type='submit']").each(function(v) {
if (Element.hasClassName(v, 'disabled')) {
v.disabled = true;
} else {
v.disabled = false;
}
});
}
Event.observe(window, 'load', function() {
fixButtons();
$$("input[type='submit']").each(function(e) {
Event.observe(e, 'click', replaceSubmit);
});
$$("form").each(function(e) {
Event.observe(e, 'submit', greySubmits);
});
});
The fixButtons is so that when people click the back button the page will fix all the buttons. And if you want to disable a button and have it not re-enable on a back you just give it a class of disabled.
document.observe("dom:loaded", function(){
$$('form').find(function(thisForm) {
Event.observe(thisForm, 'submit', function(event) {
$$('input[type="submit"]').find(function(input) {
input.value = 'Please wait ...';
input.setAttribute('disabled',true);
});
});
});
});
Here's what I came up with, which is adapted from above. Fixed so that it detects a cancelled event propagation using Prototype's stopped attribute.
Other changes include using longer variable names (I always get confused about whether e is event or element), and a function that removed the replacement inputs if the form submission is cancelled. In my implementation pressing back on the browser doesn't show the page as it was when the user left it, instead it seems to be refetched (I'm using Rails), so I've removed that part too.
I'm using buttons rather than inputs in my application so that part has changed also.
function replaceSubmit(event) {
var element = event.element();
Element.insert(element, { 'before': '<input type="hidden" name="' + element.name + '" value="' + element.value +'" class="button_replacement">'});
}
function removeReplacementSubmits() {
$$('input.button_replacement').each(function(button) {
button.remove();
});
}
function greySubmits(event) {
// Don't disable the submit if the submit was stopped with a return(false)
if (event.stopped === true) {
removeReplacementSubmits();
} else {
$$('button[type="submit"]').each(function(button) {
button.disabled = true;
button.innerHTML += '…';
});
}
}
Event.observe(window, 'load', function() {
$$("button[type='submit']").each(function(element) {
Event.observe(element, 'click', replaceSubmit);
});
$$("form").each(function(element) {
Event.observe(element, 'submit', greySubmits);
});
});

Categories