I am trying to make a form so when user click button then it will submit but the problem is that it is keep getting on function even if I am not pressing submit button. here is my code
$(function () {
var url, container, form,
View = {
init: function () {
container = $('.container');
form = $('.search#form');
console.log(form);
View.loadViews();
$(document).on('submit', '#form', View.findView());
},
findView: function () {
console.log('helllo');
return false;
},
loadViews: function (view) {
$(container).load('search.html');
}
};
View.init();
});
In code above the line $(document).on('submit', '#form', View.findView()); keeps calling findView() method whereas I want to call it when user click submit button. How can I fix this?
When you bind it using $(document).on('submit', '#form', View.findView());, you are essentially calling the function and trying to bind the submit event to what the function returns, which is incorrect. Since findView() is returning false, this is equivalent of saying $(document).on('submit', '#form', false);
You need to bind View.findView() like below:
$(document).on('submit', '#form', View.findView); // note, no () at the end
you should pass reference of function not function returned value.
$(document).on('submit', '#form', View.findView);
Related
I have submit function that is triggered on submit button inside of the form. Here is example:
$(document.body).on('submit', '#myfrm', submitFrm);
function submitFrm(e){
e.preventDefault();
var frmData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'ajax/form_data.cfm',
data: frmData
}).done(function(data){
//data saved
}).fail(function(jqXHR, textStatus, errorThrown){
alert('Error: '+errorThrown);
});
}
}
Now I would like to trigger submitFrm() function from another function like this:
function Cancel() {
submitFrm();
}
This will throw an error that e doesn't exist. I guess that submit needs to be triggered manually. Is there a way to do that with JQuery?
The error happens because you are calling submitFrm without passing the event (e). The event argument is passed by JavaScript to the function when the submit event occurs. If you call the function manually you do not have the event.
What you can do is to use JQuery to get a reference to the form element ($('#myfrm')) and trigger the submit event on hit:
function Cancel() {
$('#myfrm').submit();
}
In this way the submit event is triggered on the form and the submitFrm handler is called with the event in input.
function Cancel() {
$('#myfrm').submit();
}
according to https://api.jquery.com/submit/
Suppose there is a textbox in my webpage and I have attached an 'change' event on this textbox using jQuery.
$('.myFormClass').on('change', '.amount', function () {
// Some AJAX call here, and the response is assigned to a variable
});
And I have a form submit event as well,
$('.myFormClass').on('submit', 'form', function (e) {
// some code in which I use the response from the earlier AJAX call returned against 'change' event
});
The issue is that the 'change' event works fine individually but when form submitted they are fired almost simultaneously and till the time when AJAX call against the 'change' event is returned back (supposed to be), the form had already been submitted by then so I can't use the AJAX response, which is needed before the form submission.
Is there something built-in jQuery for this situation? If no, any alternate efficient solution?
Store the ajax promise and wait for its resolve in the form submit handler
let amountReady = null;
$('.testForm').on('change', '.amount', function(ev) {
amountReady = $.ajax({
method: 'POST',
url: 'https://httpbin.org/post',
data: {
amount: $(this).val()
}
});
});
$('.testForm').on('submit', 'form', function(e) {
e.preventDefault();
if (!amountReady) return;
amountReady.then((amountAjaxResult) => {
console.log('submit now', amountAjaxResult.form.amount);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="testForm">
<form>
<input type="number" class="amount" />
<button type="submit">Submit</button>
</form>
</div>
Add a button. When the user click the button a boolean is set to tru and if it is true then only submit will happen otherwise only onchange function will work not the submit function.
var sub=false;
$(document).ready(function(){
$('button').click(function(){sub=true;console.log(sub)})
$('.myFormClass').on('change', '.amount', function () {
// Some AJAX call here, and the response is assigned to a variable
console.log('changed')
});
$('.myFormClass').keypress((e)=>{if(e.keyCode=='13'){e.preventDefault();console.log('not submitted on enter')}})
$('.myFormClass').click( function (e) {
e.preventDefault();
console.log("submit cancelled")
if(sub)
$(this).submit();
// some code in which I use the response from the earlier AJAX call returned against 'change' event
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myFormClass">
aa
<input class="amount">
<input type="submit">
</form>
<button>Want to submit the form?</button>
You can use:
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
Or nested function after a function is done with:
function test () {
console.log('test');
}
function test2 (callback) {
console.log('test2');
callback();
}
test2(test);
Might be related
I have a modal popup that used to have a submit button.
As the content of the form is now pre filled, I want to remove the submit and have the form auto submitted.
The section of javascript that deals with this is below
afterShow: function () {
$(document).on('submit', '#back-in-stock-popup-wrapper form[name="back_in_stock"]', function () {
$.post('ajax/back_in_stock_subscribe_pop_up.php', $('#back-in-stock-popup-wrapper form[name="back_in_stock"]').serialize(), function (data) {
$('#contact_messages').html(data);
if ($('.messageStackSuccess').length) {
$('.back-in-stock-popup-wrapper-button-row').hide();
$('.back-in-stock-popup-content-wrapper').hide();
}
});
return false;
});
}
Instead of it waiting for a submit event, I want it to follow the code.
I'm hopeless with javascript and I thought I could just change it to
$(document)('#back-in-stock-popup-wrapper form[name="back_in_stock"]', function () {
but that didn't work.
How do I tell javascript to just proceed without waiting for the submit from the button click?
Just remove the outer call like so:
afterShow: function () {
$.post('ajax/back_in_stock_subscribe_pop_up.php', $('#back-in-stock-popup-wrapper form[name="back_in_stock"]').serialize(), function (data) {
$('#contact_messages').html(data);
if ($('.messageStackSuccess').length) {
$('.back-in-stock-popup-wrapper-button-row').hide();
$('.back-in-stock-popup-content-wrapper').hide();
}
});
return false;
}
So what I am trying to do is to call a function with a callback inside a submit event. What happens is that callback functions finishes after the submit event, and I want it to be vice versa.
stripeResponseHandler = function(status, response) {;
var $form = $('#new-card-details-form');
if (response.error) {
addErrorMessage(response.error.message);
return false;
} else {
var token = response.id;
$form.append($('<input id="token" type="hidden" name="token">').val(token));
}
};
$(document).ready(function() {
$('#new-card-details-form *').removeAttr('name');
Stripe.setPublishableKey('key');
var $form = $('#new-card-details-form');
$(document).on('submit', '#new-card-details-form', function(e) {
if (!$('#token').val()) {
Stripe.card.createToken($form, stripeResponseHandler);
if (!$('#token').val()) {
e.preventDefault();
}
}
});
});
So what happens here is that form submits on second click, because on the first click when I check for token existance it doesn't yet exist because the stripeResponseHandler function will complete after the submit event. Is there a way in which I can make it work with the first click? I've tried submitting the form in the stripeResponseHandler with unbind() but that didn't work too.
I have a kendo Obervable as follows:
var ViewModel = kendo.observable({
ID: 1,
TITLE: "SomeValue",
});
and then I have bound this as follows:
kendo.bind($(".bind-view"), ViewModel );
Now there is button on the page. When clicked I need to check if there are any changes to this ViewModel.
I have tried
$(".ClearAnalysisInfo").on('click', function (event) {
ViewModel.bind("change", function (e) {
//Some code
});
});
But I'm not able to get this ViewModel property whether it changed or not.
Binding the ObservableObject's change event of inside the button's click handler is too late. You need to do that immediately after the ObservableObject is created.
Inside the change handler, you will receive information about the changed field. Use this information to raise some JavaScript flag or save the details you need, so that you can use them later in the button's click handler.
var viewModelChanged = false;
var ViewModel = kendo.observable({
ID: 1,
TITLE: "SomeValue",
});
ViewModel.bind("change", function (e) {
viewModelChanged = true;
});
$(".ClearAnalysisInfo").on('click', function (event) {
if (viewModelChanged) {
// ...
}
});