I have a simple form that triggers an ajax call but as soon as the submit button is clicked the form resets and clears all entries. Do you know how to prevent this? I'd like to have control over when the form gets cleared.The code is below. I suspect I need to abandon the submit function and detect the "click" event on a button.
JQuery
$("#Formid").submit(function(){loadAjax();});
HTML
<form id="Formid" method="put">
Name<BR/>
<input type="text" name="name"/><BR/><BR/>
Node Id<BR/>
<input type="text" name="node_id"/><BR/><BR/>
Type<BR/>
<input type="text" name="type"/><BR/><BR/>
Parent<BR/>
<input type="text" name="parent_id"/><BR/><BR/>
Longitude<BR/>
<input type="text" name="longitude"/><BR/><BR/>
Latitude<BR/>
<input type="text" name="latitude"/><BR/><BR/>
Description<BR/>
<textarea name="description" rows="5" cols="40">Insert description here</textarea><BR/><BR/>
<input type="submit" value="Add Node"/>
</form>
You can use preventDefault method of the event object.
$("#Formid").submit(function(event){
loadAjax();
event.preventDefault()
})
Alternatively, you could use event.returnValue = false;
$("#Formid").submit( function(e) {
loadAjax();
e.returnValue = false;
});
This works similarly to "return false;", except it will not exit the function.
You can use e.preventDefault() or return false; within a jQuery event handler:
$("#Formid").submit(function (e) {
loadAjax();
e.preventDefault(); // or return false;
});
e.preventDefault() will prevent the default event from occuring,
e.stopPropagation() will prevent the event from bubbling up and return
false will do both.
I have prevented form clearing for search form for my website mrnams.com
View
#using (#Html.BeginForm("Search", "Home", FormMethod.Post, new { #class = "navbar-form navbar-right pull-right" }))
{
<div class="input-group">
<input id="input-searchQuery" type="text" class="form-control" placeholder="Search this site" name="q">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
}
jQuery functions in View
#section scripts{
<script type="text/javascript">
$(function () {
var queryReturned = '#ViewBag.SearchQuery';
$("#input-searchQuery").val(queryReturned);
});
</script>
}
And here is the controller.
public class Home : Controller
{
public ActionResult Search(string q)
{
ViewBag.SearchQuery = q;
}
}
For demo visit https://mrnams.com/
Related
I make some form different action within different button
<form id="form" method="post" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required>
</form>
<button type="button" class="btn btn-primary" onClick="submitForm('<?php echo base_url('order/add');?>')">Submit</button>
<button type="button" class="btn btn-warning" onClick="submitForm('<?php echo base_url('order/print');?>')">Print</button>
Javascript
function submitForm(action)
{
document.getElementById('form').action = action;
document.getElementById('form').submit(
);
}
Then, my required attribute not working. Did I do something wrong? Let me know if there is other solution.
Thanks,
I can't give you a good explanation but you need the submit buttons inside the form.
So if you would have a button like:
<input type="submit" value="Submit">,
it will trigger the required attribute.
#Remn If you would still stay on your structure with submit inside a function you could trigger yourself the validation like:
if ($("form")[0].checkValidity())
{
$("form").submit()
}
and then do something with inputs that are invalid by passing through each required element ( input is set in code ):
$('form :input[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
In the below case the invalid inputs will be focused one by one.
The whole code is:
$( function () {
$("body").on("click", "#trigger", function() {
if ($("form")[0].checkValidity())
{
$("form").submit()
}
$('form :input[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
});
});
Where #trigger is an id I set on the button to submit, you can make your own functions to achieve your goal I just used on().
I hope it helps!
Please try bellow code. i hope solve your problem.
<html>
<head>
<title>Submit</title>
<script type="text/javascript" language="javascript">
function submitForm(action)
{
document.getElementById('form').action = action;
document.getElementById('form').submit(
);
//alert(document.getElementById('form').action);
}
</script>
</head>
<body>
<form id="form" method="get" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required="required">
<button type="submit" class="btn btn-primary" onclick="return submitForm('<?php echo base_url('order/add');?>');" id="submit">Submit</button>
<button type="submit" class="btn btn-warning" onclick="return submitForm('<?php echo base_url('order/print');?>');" id="print">Print</button>
</form>
</body>
</html>
I have test your code by adding Javascript part in Script tag it is working fine. And i tested it on Chrome Windows 10.
<form id="form" method="post" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required>
</form>
<button type="button" class="btn btn-primary" onClick="submitForm('<?php echo base_url('order/add'); ?>')">Submit</button>
<button type="button" class="btn btn-warning" onClick="submitForm('<?php echo base_url('order/print'); ?>')">Print</button>
<script>
function submitForm(action) {
document.getElementById('form').action = action;
document.getElementById('form').submit();
}
</script>
Using javascript's form.submit() function will cause input validation to be bypassed (according to the HTML specification in point 4 of the form submission algorithm). The only way to trigger HTML input validation is to use a click event on a submit button inside the form, either by the user actually clicking, or in javascript with something like form.querySelector('input[type="submit"]').click().
I have a Bootstrap login form and Javascript validation:
HTML
<form id="loginForm" class="form-horizontal" role="form" action="registration.php" method="POST">
<div class="form-group">
<label class="control-label col-sm-2 modal-text" for="loginEmail">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control modal-input" id="loginEmail" placeholder="Insert email"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 modal-text" for="loginPassword">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control modal-input" id="loginPassword" placeholder="Insert password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label class="modal-text"><input type="checkbox"/> Remember me</label>
</div>
</div>
</div>
<button type="button" class="btn btn-default btn-block buttons" id="loginBtn">Login</button>
</form>
And this is my Javascript validation:
function validateEmail(id){
var $div = $('#' + id).closest('div');
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test($('#' + id).val()))
{
$div.addClass('has-error');
return false;
}
else
{
$div.removeClass('has-error');
return true;
}
}
function validateText(id){
var $div = $('#' + id).closest('div');
if($('#' + id).val() == null || $('#' + id).val() == '')
{
$div.addClass('has-error');
return false;
}
else
{
$div.removeClass('has-error');
return true;
}
}
$(document).ready(function (){
$('#loginBtn').click(function (){
if(!validateEmail('loginEmail'))
{
return false;
}
if(!validateText('loginPassword'))
{
return false;
}
$('form#loginForm').submit();
});
});
If I press login button, form submits immediately even if fields are empty.Is there something I'm missing or doing wrong?
UPDATE
What I discovered is that I put quotes around my regex expression which caused javascript error. I also changed button type from submit to button. Now it is working.
So to sum up: My validation didn't work because of quotes in regular expression. Validation will work even if I left button type submit.
Use onsubmit instead of onclick, and return true when the form is valid.
In your case, the onclick event will be fired, correctly return false, and then as the button is still a submit type, it will still submit the form.
It submits anyway, because the button is a submit button:
<button type="submit"
The return false from the click handler cancels the click event, but no other events - ie the submit event still fires.
You can change the button to type=button and then submit the form in the click handler (which you're already doing):
<button type="button"
You have used button with type="submit" and method="POST". So, when you click button it is immediately submitting form. Try type="button" for your submit button.
Stop event handling, probably you don't want to do anything else than to submit form if it is valid
$('#loginBtn').click(function (Evt){
Evt.stopPropagtion();
Evt.preventDefault();
if(!validateEmail('loginEmail'))
{
return false;
}
if(!validateText('loginPassword'))
{
return false;
}
$('form#loginForm').submit();
});
I have this code in html.
<form method="POST" data-bind="submit: submitComment">
<label for="comment">
<textarea name="comment" data-bind="value: commentTextArea"></textarea>
<button type="submit">Submit</button>
</label>
</form>
and this is my knockout viewmodel
this.commentTextArea = ko.observable('');
this.submitComment = function(formElement) {
alert("I'm being posted!");
return false;
}
My problem is that when I submit the form the return false; row is ignored, thus submittinig the form "for real". I can verify that I am in the submitComment() method since the alert is fired.
I've read the knockout guide and several examples but no example even say I would need the return false; line.
The goal is to prevent the event from bubble. Thanks
I solved it by changing the data-bind-type to an event like this
<form method="POST" data-bind="event: { submit: submitComment }">
<label for="comment">
<textarea name="comment" data-bind="value: commentTextArea"></textarea>
<button type="submit">Submit</button>
</label>
</form>
By changing to an event I get the event-parameter that I use to stop propagating like this
this.commentTextArea = ko.observable('');
this.submitComment = function(formElement, event) {
event.stopPropagation();
}
I want to perform validation before any other onsubmit actions. Unfortunately, I have no control over the value of the onsubmit attribute on the form. So for example:
<form id="myForm" onsubmit="return stuffICantChange()"></form>
I've tried the following code, and several other methods, with no luck:
$("#myForm").onsubmit = function() {
console.log("hi");
}
Any help is appreciated, thanks.
If this is a duplicate, please let me know before marking it as such so that I can refute the claim if necessary.
EDIT:
My code as requested:
<form id="form_ContactUs1" name="form" method="post" action="index.php" onsubmit="return Validator1(this) && ajaxFormSubmit(this); return false">
<div class="form">
<div class="form-staticText">
<p>We look forward to hearing from you! Please fill out the form below and we will get back with you as soon as possible.</p>
</div>
<div class="form-group">
<input class="form-control" placeholder="Name" id="IDFormField1_Name_0" name="formField_Name" value="" size="25" required="" type="text">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" id="IDFormField1_Email_0" name="formField_Email" value="" size="25" required="" type="email">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control bfh-phone" data-format="ddd ddd-dddd" placeholder="Phone" id="IDFormField1_Phone_0" name="formField_Phone" value="" size="25" type="tel">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Comments" name="formField_Comments" id="IDFormField1_Comments_0" cols="60" rows="5" required=""></textarea>
<span class="form-control-feedback"></span>
</div>
<div class="row submit-section">
<input name="submit" class="btn btn-success submit-button" value="Submit" type="submit">
</div>
</div>
$( "form" ).each(function() {
console.log( $(this)[0] );
sCurrentOnSubmit = $(this)[0].onsubmit;
$(this)[0].onsubmit = null;
console.log( $(this)[0] );
$( this )[0].onsubmit( function() {
console.log( 'test' );
});
});
You should be able to add unobtrusively another onsubmit function to #myForm, in addition to the function which already executes:
function myFunction() {
...
}
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',myFunction,false);
Try
$("#myForm").submit(function(){
.. Your stuff..
console.log("submit");
return false;
});
This will trigger everytime the form is submitted then the end return false stops the forms default actions from continuing.
Try this, it is plain Javascript:
function overrideFunction(){
console.log('Overrided!');
}
var form;
form = document.querySelector('#myForm');
form.setAttribute('onsubmit','overrideFunction()');
Regards.
You should trigger a change event on every field in the form to check on validation.
$('input').on('change', function(e) {
if($(this).val() == '') {
console.log('empty');
}
});
This wil help the user mutch faster then waiting for the submit.
You could also try a click event before the submit.
$('#formsubmitbutton').on('click', function(e) {
//your before submit logic
$('#form').trigger('customSubmit');
});
$('#form').on('customSubmit', function(e) {
//your normal submit
});
Try this code:
$("#myForm").on('submit',function() {
console.log("hi");
});
Stumbling across this post and putting together other javascript ways to modify html, I thought I would add this to the pile as what I consider a simpler solution that's more straight forward.
document.getElementById("yourFormID").setAttribute("onsubmit", "yourFunction('text','" + Variable + "');");
<form id="yourFormID" onsubmit="">
....
</form>
I have written very simple code, here is the html code:
<form name="signInForm">
<section id="signInSection">
<input class="large" type="text" placeholder="username" />
<br>
<input class="large" type="password" placeholder="password">
<br>
<button id="signinbtn" class="small">Sign In</button>
<br>
<label><input type="checkbox" />Remember me.</label>
Reset Password
<img src="../images/cancel.jpg" alt="Cancel Sign In">
</section>
</form>
And here is the jQuery:
$('#signinbtn').on('click', function () {
$('#signInSection').fadeOut(200);
$('#signedInSection').fadeIn(200);
$('.signUp').fadeOut(1);
$('.signIn').closest('header').find('input').fadeIn(200);
$('#memberToolBarSection').fadeIn(1500);
$('#contents').fadeIn(1500);
});
Whatever I write inside the above mentioned click handler, it is not working. Although I tested by putting an alert that the handler is getting invoked.
Can anyone please tell me why it is not invoking all the fadeIn and fadeOut function calls?
Try this...
$('#signinbtn').on('click', function (e) {
e.preventDefault();
$('#signInSection').fadeOut(200);
$('#signedInSection').fadeIn(200);
$('.signUp').fadeOut(1);
$('.signIn').closest('header').find('input').fadeIn(200);
$('#memberToolBarSection').fadeIn(1500);
$('#contents').fadeIn(1500);
});
It looks like the form is being submitted, which in this case just reloads the page.
Adding the e parameter to the event handler and adding e.preventDefault() will stop the form submitting.
Here's a working example
Is it not because the form is being submitted so you're being redirected? If that is the case, change your handler to the following:
$('#signinbtn').on('click', function (e) {
e.preventDefault();
$('#signInSection').fadeOut(200);
$('#signedInSection').fadeIn(200);
$('.signUp').fadeOut(1);
$('.signIn').closest('header').find('input').fadeIn(200);
$('#memberToolBarSection').fadeIn(1500);
$('#contents').fadeIn(1500);
});
The crucial line being
e.preventDefault();
Working DEMO
Try this
e.preventDefault(); prevent it from submitting the form after animations $("#signInForm").submit(); will submit the form where signInForm is the form id
html
<form name="signInForm" id="signInForm">
<section id="signInSection">
<input class="large" type="text" placeholder="username"/><br>
<input class="large" type="password" placeholder="password"><br>
<button id="signinbtn" class="small">Sign In</button><br>
<label><input type="checkbox"/>Remember me.</label>
Reset Password
<img src="../images/cancel.jpg" alt="Cancel Sign In">
</section>
</form>
code
$('#signinbtn').on('click', function (e) {
e.preventDefault();
$('#signInSection').fadeOut(200);
$('#signedInSection').fadeIn(200);
$('.signUp').fadeOut(1);
$('.signIn').closest('header').find('input').fadeIn(200);
$('#memberToolBarSection').fadeIn(1500);
$('#contents').fadeIn(1500);
$("#signInForm").submit();
});
Try This one
$('form').on('click', '#signinbtn', function () {
$('#signInSection').fadeOut(200);
$('#signedInSection').fadeIn(200);
$('.signUp').fadeOut(1);
$('.signIn').closest('header').find('input').fadeIn(200);
$('#memberToolBarSection').fadeIn(1500);
$('#contents').fadeIn(1500);
});