Why is a form's submit event not firing (jQuery)? - form-submit

I have a form + layout like so:
<form ...>
<div id="editor">
[form html]
<input type="submit" value="Submit form" />
</div>
</form>
And the following javascript:
$(function() {
var form = $('#editor').parents('form');
alert(form.length); // this alerts "1"
$(document).on('submit', 'form', function() {
alert('document form submit fired'); // this works as expected (alerts)
});
form.on('submit', function() {
alert('selected form submit fired'); // this is never alerted
});
});
This form is not loaded via ajax. When the page loads, the first dialog alerts "1". However when submitting the form, only one alert is fired -- the one that triggers submit for all forms in the document.
Why would this happen?

It does work. Something else is happening which is preventing the second alert from firing.

Your form selector is incorrect.
Try and do this
$("form").on('submit', function() {
Pretty sure this should work
Actually if nothing is being loaded through ajax or dynamically through javascript
You can just do
$("form").submit(function() {
EDIT
Scratch my above. Didn't see you set the value of form. Check out http://jsfiddle.net/s3fvM/1/. Seems to be working fine to me. both are firing and alerting.

Related

Laravel: Two form with one submit button

I want to submit two form into two url and want to submit from two another functions of a Controller.
<form method="post" url="{ '/url1' }">
</form>
<form method="post" url="{ '/url2' }">
</form>
<button type="submit">Submit</button>
Is it possible to do without AJAX??
Simple answer : no, without ajax you can't send two requests.
Complicated answer: unless the first one carries the data for both then in the first response, it sends the second request with the data for it. Which is so complicating things, you should just do it in one request.
You can use jQuery to submit both forms like in the example below:
First of all, add an id to your button like this
<button type="submit" id="submitBtn">Submit</button>
Add ID to your forms:
form method="post" id="form1" url="{ '/url1' }">
form method="post" id="form2" url="{ '/url2' }">
I don't know what is wrong with the stakoverflow editor, that is why i deleted the "<" sign.
3. Now handle the jQuery click event:
$(document).ready(function(){
$('#submitBtn').on('click',function(){
$('#form1').submit();
$('#form2').submit();
});
});
You could give the forms different ids but same action.
Then in the controller called by the submit button, let IF statements check for the form ids and return the respective view desired eg
$requests = $request->all();
$form_Id = $requests['form1_Id'];
if($form_Id != 'id_of_first_form') {
return view('url2');
}else{
return view('url1');
}
If you have a main page form and a modal form and you wanna submit both in order, you can do it with javascript like this
// cause double submits at once
function doubleSubmit()
{
$.post($('#recordPaymentForm').attr("action"), $('#recordPaymentForm').serialize(), function(response) {
$('#submitEditOrderButton').trigger('click');
});
return false;
}
Leave your main page form as it is and change your modal form on submit attribute like this
<form id="recordPaymentForm" method="POST" action="/orders/{{$order->id}}/payments" onsubmit="return doubleSubmit(event)">
Please not that we first submit modal form and then we trigger on click event of submit button (submitEditOrderButton) on the main page. In this example, we first submit payment form and then we trigger click event of main page form which cause a form submit on the main page.

MVC3 C# Disabling the Validation Messages on Cancel

I have an MVC2 C# .Net Web App. We are using the built in MVC3 Validation using the Domain class properties [Required(ErrorMessage = "Start From is required.")] and in the HTML #Html.ValidationMessageFor(model => model.StartFrom)
However, when we submit the page using the Cancel button, the validation is fired stating the "Start From is Required" and therefore not exiting the page. How can I disable the Validation on the Cancel button? Or submit the page without firing the Validation?
I think you need to override the default behaviour of the submit button i.e., Cancel button in your case.
Say you have the cancel button like this:
<input type="submit" id="btnCancel" value="cancel"/>
now write the jQuery to override the default behaviour
$(function(){
$('#btnCancel').click(function(e){
e.preventDefault();
//or you can return false from this method.
//return false;
});
});
I found an answer here, on Stackoverflow :) jQuery disable validation
Each of the first two answers in that link worked for me. #Karthik, thanks for the answer. It got me on the right track
Answer 1:
<input id = "theCancel" class="cancel" type="submit" value="Cancel" />
Answer 2:
$(function () {
$('#theCancel').click(function (e) {
$("form").validate().cancelSubmit = true;
});
});
I chose answer 2 and put it in our global js file. All of our Cancel buttons have an id of "theCancel"

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

ASP.NET MVC - Having a confirmation button with a Form

I have an strongly typed view for my model and what I'd like is that when the user clicks on submit, a confirmation box pop up confirming that the user does indeed wish to submit the form, if they click cancel then it shouldn't fire the HttpPost Action for that View, is this possible?
Of course it is possible. I like to use an unobtrusive approach. Here is a simplified example:
jQuery(document).ready(function () {
jQuery('[data-confirm]').click(function (e) {
if (!confirm(jQuery(this).attr("data-confirm")))
{
e.preventDefault();
}
});
});
Then you only need to add a data-confirm attribute to your submit button for example
<input type="submit" data-confirm="are u sure?" />
Of course you can use this attribute on links, buttons, etc. you are not restricted to submit buttons only, and if you want to implement a fancier confirm dialog later than you will have to replace the code only in one place.
function doSubmit()
{
if(window.confirm("ARE YOU SURE TO PERFORM THIS ACTION"))
{
return true;
}
else return false;
}
call doSubmit() function on onsubmit event of the form,
Eg- onsubmit="return doSubmit()
you can add a simply jQuery call for that.
at the end of your view add:
<script type="text/javascript">
$("form").submit(function() {
return confirm('Are you sure?');
});
</script>
or, add a
onsubmit="return confirm('Are you sure?');"
as a new element property
I believe this can be done by overriding the submit button using jquery. Jquery .submit()
This way, when the person hits submit you can show a message and either submit it or cancel it.

this.form.submit vs. submit button

I am trying to auto submit a form after a zip code is entered that will trigger the display of a google map.
The code works fine if I use a submit button with the form. The form submits and the ajax code does it's thing and the div is replaced with the google map that corresponds to the zip code.
However, if I try to auto submit the form using the code below:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#htmlExampleTarget' // target element(s) to be updated with server response
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind to the form's submit event
$('#htmlForm').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
});
<form id="htmlForm" action="html-echo.php" method="post">
Message: <input type="text" name="message" onKeyUp="if(this.value.length>4)this.form.submit()">
<div id="htmlExampleTarget">
<script type="text/javascript">
$(function()
{
$("#map").gMap({ address: "Los Angeles", zoom: 13 });
});
</script>
<div id="map" style="width: 547px; height: 320px; border: 1px solid #777; overflow: hidden;"></div>
</div>
All that happens is that the forms action (action="html-echo.php") page is loaded.
How can I make this.form.submit behave the same as a submit button?
Thank you!
The DOM method form.submit() doesn't trigger submit handlers. Since you are using jQuery, use $(this.form).trigger("submit") instead.

Resources