Need help with a form submission using javascript or jquery - javascript

I have a form which looks like this
#using (Html.BeginForm("ActionMethod","MyController FormMethod.Post)) {
<button type="submit" value="Generate" name="action" class="button" id="btnGenerate">Generate Form</button>
<button type="submit" value="Confirm" name="action" class="button" id="btnConfirm">Confirm</button>
}
and my javascript looks like this
<script type="text/javascript">
$(function () {
var genOverlay = jQuery('<div id="overlay"><div class="innerblock box-shadow"><p>Please remember to print the registration form and sign both copies.</p><div><a id="btnClose" href="#" class="button">Close</a></div></div>');
var confirmOverlay = jQuery('<div id="overlay"><div class="innerblock box-shadow"><p>Changes can not be made to this record once it has been confirmed. Are you sure you would like to confirm this form?</p><div> <a id="btnConfirmConfirmation" href="#" class="button">Confirm</a> <a id="btnCancel" href="#" class="button button-red">Cancel</a></div></div>');
$('#btnGenerate').click(function () {
genOverlay.appendTo(document.body);
return false;
});
$('#btnConfirm').click(function () {
confirmOverlay.appendTo(document.body);
return false;
});
$('#btnConfirmConfirmation').live('click', function () {
// Need help on submitting the form with the input button value of btnConfirm.
// $('#btnConfirm').submit(); does not work
// return true;
});
$('#btnClose').live('click', function () {
genOverlay.remove();
});
$('#btnCancel').live('click', function () {
confirmOverlay.remove();
});
});
</script>
How would i go about implementing btnConfirmConfirmation click on the overlay to just submit the form normally with the action value of "Confirm"?
Thanks for any help

The .submit() method only applies to <form> elements. You could add an id to your form:
<form id="myForm" ...>
Which, as you're using HtmlHelper to create it would be achieved with:
#using (Html.BeginForm("ActionMethod","MyController", FormMethod.Post, new { id = "myForm" })) { ...
And then call the submit method (documented here) on that:
$('#btnConfirmConfirmation').live('click', function () {
$('#myForm').submit();
});
Or you could go to the form for your button by finding the closest ancestor form element for the button:
$('#btnConfirmConfirmation').live('click', function () {
$(this).closest('form').submit();
});
closest method is documented here.

submit is an event handler of the form element. This should work:
$('#btnConfirm')[0].form.submit()
//All form elements have a property called "form" which refers to the parent form
If you've attached an identifier to your form, use this:
$('#formId').submit(); //<form id="formId" ...
$('form[name="formName"]').submit(); //<form name="formName" ...

Related

Preventing Jquery QueryBuilder from refresh after 'getRules' called

I am using Jquery Query Builder inside HTML form
<script type="text/javascript">
......
......
var filter_json2 = <%=jsonArray%>;
console.log(<%=jsonArray.toString()%>);
$(document).ready(function(){
$('#rule_div').queryBuilder({
plugins:['bt-tooltip-errors'],
filters:filter_json2
});
$('#btn_reset').on('click', function () {
$('#rule_div').queryBuilder('reset');
});
$('#btn_set').on('click', function () {
$('#rule_div').queryBuilder('setRules', rules_basic);
});
$('#btn_get').on('click', function () {
var result = $('#rule_div').queryBuilder('getRules');
if (!$.isEmptyObject(result)) {
//alert(JSON.stringify(result, null, 2));
$("#jsonRule").val(JSON.stringify(result, null, 2));
console.log(result);
}
});
});
......
......
</script>
......
......
......
......
<form action="/jspfile.do" method="post">
......
......
other fields in form
......
......
<tr>
<td></td>
<td>
<div id="rule_div">
<button class="btn_set" id="btn_set">Set Rules</button>
<button class="btn_get" id="btn_get">Get Rules</button>
<button class="btn_reset" id="btn_reset">Reset</button>
</div>
<input type="hidden" id="jsonRule" name="jsonRule" value="">
</td>
</tr>
</form>
when I select something from Query Builder and hit get rules button I am getting json rules but page is getting refreshed and whatever I have selected is getting erased..
This is not the case with demo I am referring [https://querybuilder.js.org/demo.html]
Can anyone please suggest me , How can I prevent selected data from query builder from erasing after refresh?
You are in a form, and any untyped button in a form is a submit button.
if you add type="button" to your buttons it should stop them from submitting your form.
Another solution is indeed to always call preventDefault
$('#btn_get').on('click', function (e) {
e.preventDefault();
// custom action here
});

form.submit() not working

I need to do something to use the ruby cgi to output something.
As such form must be submitted first followed by the js to alter the element values.
Using the form.submit() does not work in my case.
Using the simple below example below to output the click me values after submitting the form.
When the form.submit() function is run,the js will not work on click me.
Form onsubmit method cannot be used as it calls the javascript function first before submitting the form(Must submit the form first then call the JS function to carry out something)
Any idea to resolve this:
NOTE:MUST SUBMIT FIRST
$(document).on('click','#afterbutton',function() {
var form = document.getElementById("myForm");
//form.submit();
document.getElementById("test").innerHTML = "afterbutton";
});
$(document).on('click','#beforebutton',function() {
var form = document.getElementById("myForm");
//form.submit();
document.getElementById("test").innerHTML = "beforebutton";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="submit" value="formSubmitbutton" id="submit"><br>
<button id="beforebutton">beforebutton</button><br>
</form>
<button id="afterbutton">afterbutton</button><br>
<p id="test">click me</p>
OK easy problem , you make a simple mistake when you give an input the id submit you override the form.submit method if you look at the console in the devtool you'll see something telling you that
form.submit is not a function
so to solve this problem change the id of your first input instead of submit to something else like submit123
<input type="submit" value="formSubmitbutton" id="submit123"><br>
look at the code below and tell me what you think
$(document).on('click','#afterbutton',function(event) {
event.preventDefault();
var form = document.getElementById("myForm");
form.submit();
document.getElementById("test").innerHTML = "afterbutton";
});
$(document).on('click','#beforebutton',function(event) {
event.preventDefault();
var form = document.getElementById("myForm");
form.submit();
document.getElementById("test").innerHTML = "beforebutton";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="submit" value="formSubmitbutton" id="submit123"><br>
<button id="beforebutton">beforebutton</button><br>
</form>
<button id="afterbutton">afterbutton</button><br>
<p id="test">click me</p>

jQuery validate is not working when the button is outside the form

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();
});
});

form onsubmit ignores action

I am new to JavaScript. I have a form with an action and I need to fill the form inputs using JavaScript on submitting. I use an onsubmit function which executes as expected, but the form didn't hit the action in the action attribute and no data is sent to the server.
Can anybody help me find what is missing ?
JavaScript/jQuery:
$("#myForm").submit(function (e) {
e.preventDefault();
return fillFormValues();
})
function fillFormValues()
{
$.get( ...,function( data ) {
//fill my inputs values here
return true;
});
return false;
}
HTML:
<form action="..." method="post" target="output_frame" id="myForm">
<input name="first" id="first" type="hidden" value="">
...
<input type="submit" value="next">
</form>
what you can do is prevent the jQuery event default that would submit the form, do the ajax and once values are set trigger the native submit event that will bypass the jQuery submit listener
$("#myForm").submit(function(e) {
e.preventDefault();
fillFormValues(this);
});
function fillFormValues(form) {
$.get(..., function(data) {
//fill your inputs values here
form.submit(); //trigger native submit which is not caught by jQuery
});
}

How to submit three forms with one submit button

I have 3 forms I would like to submit with one button:
<form id="#formEditUsername">
//Code
</form>
<form id="#formEdituseremail">
//Code
</form>
<form id="#new_password_form">
//Code
</from>
<button type="submit" class="btn btn-success" id="btnUpdate">Save</button>
I understand that the best way to do this is probably Ajax, but am unsure how I would do this; create two AJAX functions for the first two forms and then call the functions when the third is submitted?
Try this
$(document).ready(function() {
$("#btnUpdate").click(function() {
$.post($("#formEditUsername").attr("action"), $("#formEditUsername").serialize(),
function() {
$.post($("#formEdituseremail").attr("action"), $("#formEdituseremail").serialize(),
function() {
$.post($("#new_password_form").attr("action"), $("#new_password_form").serialize(),
function() {
alert('All forms submitted');
});
});
});
});
});
As #Jari mentioned, you can simply collect data from first two forms and submit them all together.
Note: this aproach requires input name attributes to be unique among all three forms.
Simple example of AJAX call:
var firstFormData = $("#formEditUsername").serialize();
var secondFormData = $("#formEdituseremail").serialize();
var thirdFormData = $("#new_password_form").serialize();
$.post(
URL, // target URL of your choice
firstFormData + secondFormData + thirdFormData
);
<form id="#formEditUsername" class="frmToSubmit" method="post">
//Code
</form>
<form id="#formEdituseremail" class="frmToSubmit" method="post">
//Code
<form>
<form id="#new_password_form" class="frmToSubmit" method="post">
//Code
</from>
<script type="text/javascript">
$(document).ready(function() {
$("#btnUpdate").click(function() {
$(".frmToSubmit").submit();
});
});
</script>

Categories

Resources