I am submitting a form using AJAX. The fields are in a partial view that get sent to a controller action. The partial view is in a div that pops up when a button on the main form is clicked. If the user completes the form and clicks the submit button it then the update is performed in the controller action and all is well. However, if the user changes their mind I like to add a cancel button to hide the form. Adding the button and hiding the form works as expected, but the call to the controller action method still occurs. I've tried using
e.preventDefault();
but this hasn't worked.
I've tried using a second JQuery method attached to the cancel id but I can't get this to work.
My JQuery looks like this:
$('#VisitorModal').on('submit', '#visitorform', function (e) {
var data = $(this).serialize();
var url = '#Url.Action("CreateVisitor", "Meetings")';
var text = $('#title').val() + ' ' + $('#firstname').val() + ' ' + $('#surname').val() + ' (' + $('#company').val() + ')'; // a value from the form that you want as the option text
$.post(url, data, function (response) {
if (response) {
$('#VisitorID').append($('<option></option>').val(response).text(text)).val(response);
} else {
dialog.hide();
}
}).fail(function () {
dialog.hide();
});
dialog.hide();
e.preventDefault();
//return false; // cancel the default submit
});
$('#cancel').on('click', function () {
dialog.hide();
});
And here's my action method:
[HttpPost]
public JsonResult CreateVisitor(AppointmentViewModel model)
{
var visitor = new Visitor()
{
Title = model.VisitorTitle,
FirstName = model.VisitorFirstName,
LastName = model.VisitorSurname,
Company = model.VisitorCompany
};
db.Visitors.Add(visitor);
db.SaveChanges();
return Json(visitor.id);
}
And submit & cancel buttons here:
<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<input type="submit" value="Create" class="btn btn-success" id="submit" />
<input type="button" value="Cancel" class="btn btn-warning" id="cancel" />
</div>
</div>
Does anyone have any suggestions that might get this to work as I hope?
Since your form is being loaded dynamically after the initial page has been rendered, you need to use event delegation by using .on() to add a listener to an ancestor that exists when the page is rendered
Instead of
$('#cancel').on('click', function () {
dialog.hide();
});
use
$(document).on('click', '#cancel', function () {
dialog.hide();
});
but replace document with the closest ancestor that exists when the page is first generated.
Related
I have a problem where jQuery validate is not working when the submit button is placed outside the form tags (which is required form my Cordova mobile app). As soon as .validate is called, the execution stops.
My HTML is set-up this way:
<form id="form-cart" >
// All form fields here
</form>
<ons-bottom-toolbar>
<button class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
And the function is then called as:
function addToBasket()
{
$.validate({
form : '#form-cart',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
// Run ajax on success
}
};
sNavigator.pushPage("confirmation.html", options);
return false;
}
});
}
How can I get this working so that it validates and calls ajax even if the button is outside of the form tags?
According to jQuery validation plugin documentation there are two different methods:
validate() – Validates the selected form.
valid() – Checks whether the selected form or selected elements are valid.
So you should set up the form validation with .validate method outside your function and check if form is valid inside your function (see code example below):
$('#form-cart').validate({
});
function addToBasket() {
if ($('#form-cart).valid())
//do you onSuccess stuff
}
}
Try this :
<form id="form-cart" >
// All form fields here
// Don't give <input type="submit"> here
</form>
<ons-bottom-toolbar>
<button type="submit" id="submitBtn" class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
and
$(document).ready(function () {
$("#submitBtn").click(function () {
$("#form-cart").submit();
});
});
I am writing an AJAX function in ASP.Net MVC5 and I am getting a problem that the form AJAX request goes only one time. It is a search page. After I choose the filter I press search I get the correct result. However if I changed the filter and click the search submit again, nothing will happen.
var ajaxFormSubmit = function() {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var target = $($form.attr("data-enbw-target"));
target.replaceWith(data);
debugger;
});
return false;
};
$("form[data-enbw-ajax='true']").submit(ajaxFormSubmit);
<form method="get" id="documentForm" action="#Url.Action("Index", "DocumentSearch")" def data-enbw-ajax="true" data-enbw-target="#documentSearchResult">
<button type="submit" id="submitbtn" name="submitbtn" tabindex="100" class="k-button">
<img src="~/Content/search_small_icon.png" />
#WebResources.DocumentSearchButton
</button>
</form>
#Html.Partial("Results", #Model)
public ActionResult Index(DocumentSearchInput model)
{
if (Request.IsAjaxRequest())
{
return PartialView("Results", result);
}
return View(result);
}
I do not get any error. and when I get a debugger; in javascript. the new data is correct. can you please help me.
You are replacing the form in your ajax success. As such, the new form will not have the submit binding on it. If you truely want to do this you will have to rebind to the new form, or possibly use a delegate instead.
$('parentSelector').on('event', 'childSelector', function(){});
parentSelector - A parent element of the child that pre-exists the child element and should typically not be removed/created during the page lifespan.
childSelector - A selector for the element that will be created/changed/removed at some point in the lifespan of the page.
I found the answer.
the problem wasn't with the submit. the problem was with re-writing the data.
$.ajax(options).done(function (data) {
$("#documentSearchResult").empty();
$("#documentSearchResult").html(data);
});
simply, I empty the div then write inside.
My goal is to click a button and upon click show a confirm box using bootbox. If I select ok it should postback, if I click cancel it should do nothing. Currently, when I click the button it posts back before showing the confirm box, so it appears then immediately disappers.
Script
<script>
function DeleteDeliverables(e,myform) {
e.preventDefault();
bootbox.confirm("Are you sure you would like to delete the selected deliverables? They will be permanently deleted", function (result) {
if (result) {
var deliverables = "";
var cbs = document.getElementsByTagName('input');
for (var i = 0; i < cbs.length; i++) {
if (cbs[i].type === 'checkbox') {
if (cbs[i].checked) {
deliverables += cbs[i].value + ',';
}
}
}
deliverables = deliverables.replace(/,\s*$/, "");
document.getElementById("hiddenDeliverable").value = deliverables;
myform.submit();
}
});
}
</script>
Button
<input type="submit" name="submitButton" class="btn btn-default" value="Delete" onclick="DeleteDeliverables(event,this.form)" /></td>
Postback
[HttpPost]
public ActionResult DeliverableManagement(string submit, DeliverableManagementModel model)
{
//omitted
}
You left out the argument when you call DeleteDeliverables(). It should be:
onclick="DeleteDeliverables(event)"
If you check your Javascript console, you'll probably see an error because undefined.preventDefault is not a function. Since you're not preventing the default action, clicking on the submit button submits the form.
You also need to put
document.getElementById("formID").submit();
in the bootbox.confirm() callback function, since preventDefault prevents the normal form submission.
Finally, for that to work, you need to use a different name for the submit button. Change name="submit" to something like name="submitButton". Otherwise, document.getElementById("formID").submit will refer to the button (because input names are properties of the form), not the function that submits the form.
The click event on my submit button triggers a confirmation modal.
When the user clicks on the confirmation button, the form is sent without the original submit button data, which I need.
Simplified code:
<form action="/action" method="post">
<!-- inputs -->
<button type="submit" name="foo" class="with-confirmation-modal" />
</form>
<script>
$(document).on('click', '.with-confirmation-modal', function() {
$form = $(this).closest('form');
$modal = $('#modal');
$modal.on('click', 'button[type=submit]', function() {
// form is sent without the info about which button
// was clicked prior to modal
$form.submit();
return false;
});
$modal.modal('show');
return false;
});
</script>
What's a good way to deal with this ?
When you post a form clicking on
<button type="submit" name="foo" />
data posted includes the name of the button :
...&foo=&...
This behaviour is broken by the confirmation popup. Here we simulate it by adding a hidden input with the name of the clicked button before calling $form.submit().
<script>
$(document).on('click', '.with-confirmation-modal', function() {
var $clickedBtn = $(this);
var $form = $clickedBtn.closest('form');
$modal = $('#credit-headsup-modal');
$modal.on('click', 'button[type=submit]', function() {
$(this).parent('.btn-wrapper').addClass('btn-wrapper--active');
$(this).siblings('.btn-loading').show();
// Pass info about which btn was clicked prior to modal
// by adding a hidden input with same name as btn
$form.append('<input type="hidden" name="'+$clickedBtn.attr('name')+'" value="">');
$form.submit();
return false;
});
$modal.modal('show');
return false;
</script>
If there is a better way, please share.
Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.