I have a really strange problem. My Jquery based form appears to be submitting its self twice.
It only happens when I use the following code to submit my form:
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
When I use the following, I do not get the double submit:
<input type="submit" value="Transfer" class="btn btn-success dark" id="transfer-button"/>
Here is the code in context:
FORM:
<form class="form-horizontal hidden" id="transfer-form" novalidate>
<fieldset>
<div class="control-group">
<div> </div>
<div class="controls">
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
</div>
</div>
</fieldset>
</form>
And the JQuery code:
$('#transfer-form').submit(function()
{
event.preventDefault();
//run some error checks
if (messageArray.length !== 0)
{
//Return errors
} else {
$('#transfer-button').prop('disabled', true);
$('#transfer-spin').addClass('fa-spin');
var url ='/api/transfer';
$.ajax({
//Do the ajax call...
You need to pass the event as parameter in submit:
$('#transfer-form').submit(function(event)
Your submit function needs to receive the event object
function (event) {
...
I believe you have to specify the event variable in the function, with that you can prevent default behavior.
$('#transfer-form').submit(function(event)
{
event.preventDefault();
...
}
Related
I am building angular2 form and I would like to have multiple buttons to submit the form, e.g "Save" and "Save and close".
I have tried to use simple buttons with click action on them, but I didn't find anyway to manually mark form as submitted to force form validation.
<form #ticketForm="ngForm" novalidate>
<input type="text" id="customerName" required
name="customerName" [(ngModel)]="ticket.customerName"
#customerName="ngModel">
<div class="tj-form-input-errors"
*ngIf="customerName.errors && (customerName.dirty ||
customerName.touched || ticketForm.submitted)">
<small [hidden]="!customerName.errors.required">
Customer name is required
</small>
</div>
<button type="button" (click)="save(ticketForm)">Save</button>
<button type="button" (click)="saveAndClose(ticketForm)">Save and close</button>
</form>
Assign different id to each button. Then you can obtain the id of the button which triggered submit using document.activeElement.id. like the following :
In your Html :
<form #form="ngForm" (submit)="firstSave(form,$event)">
...
<div class="form-group">
<input type="submit" id="submit-1" value="Submit 1" class="btn btn-sm btn-primary"/>
<input type="submit" id="submit-2" value="Submit 2" class="btn btn-sm btn-success"/>
</div>
</form>
Then in your typescript :
firstSave(form: NgForm, $event: Event) {
var activeButton = document.activeElement.id; // document.activeElement?.id
if (activeButton == "submit-1") {
alert("you have clicked on submit 1");
}
if (activeButton == "submit-2") {
alert("you have clicked on submit 2");
}
}
StackBlitz Here.
You can subscribe to form changes, which I think will fire form validation.
I do something like this:
this.physicalForm.valueChanges
.map((value) => {
return value;
})
.filter((value) => this.physicalForm.valid)
.subscribe((value) => {
do what you need with the values here...
});
Then in your click handler for each button, if this.physicalForm.valid you save or save&update.
i ran into the same situation. In my case i have 2 submit 'Save','Save and Allocate'
Solution
You can simply set the the type of submit button in the payload and do the action accordingly in the backend code.
Sample code
//here formData is my payload for the API call eg: formData.name,formData.email
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='save'">Save</button>
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='allocate'">Save And Allocate</button>
I am looking for a way to check, if the url a user have posted in my form is a valid facebook url. I am aware of the regx (?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?
But how to use it, am i not sure on how to do?
<div class="col-sm-6">
<div class="col-sm-12">
<b>Facebook Url</b>
<input id="FacebookUrl" name="FacebookUrl" type="text" class="form-control" />
</div>
<div class="col-sm-12">
<button id="SendBtn" class="btn btn-success pull-right">Send</button>
</div>
</div>
How can i make a form validation on that, that checks the facebook regx? Thanks
In the button onclick event:
<button id="SendBtn" class="btn btn-success pull-right" onclick="return validateUrl();">Send</button>
And then you can open a script tag in the same file or other file and implement your regex.
function validateUrl() {
url = $("#FacebookUrl").val();
var pattern = /^(?:(?:http|https):\/\/)?(?:www.)?facebook.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[?\w\-]*\/)?(?:profile.php\?id=(?=\d.*))?([\w\-]*)?$/;
if(pattern.test(url)) {
alert("Correct URL");
}
else {
alert("Incorrect URL");
}
return pattern.test(url);
}
And with this result prevent the action.
I have a form which I am trying to use JS to cancel, so that I can submit it using Ajax.
However I just started and as I made the form and tested to see if the submission is cancelled/return's false I discovered that it did not. I checked other threads/posts made but none helped me. This is my form bellow, followed by the .js file. The console in chrome has not given me any errors either.
EDIT: I forgot to mention that the alert in the .js file is not coming up either.
<form method="post" class="form-horizontal form-bordered" id="user-data-form">
<div class="form-group">
<label class="col-md-3 control-label" for="oldpassword">Old Password</label>
<div class="col-md-6">
<input type="password" id="oldpassword" name="oldpassword" class="form-control" placeholder="Old Password">
</div>
</div>
<div class="form-group form-actions">
<div class="col-md-9 col-md-offset-3">
<!-- Submit element -->
<input type="submit" class="btn btn-effect-ripple btn-primary" value="Update">
<!-- END Submit element -->
</div>
</div>
</form>
And the JS file,
$( '#user-data-form' ).submit( function(event) {
alert( "Handler for .submit() called." );
event.preventDefault();
return false;
});
I suggest you try making the event.preventDefault(); the first thing that runs as the alert maybe allowing the normal button pressing function of a HTML form to get run while the alert sits on screen
$( '#user-data-form' ).submit( function(event) {
event.preventDefault();
alert( "Handler for .submit() called." );
return false;
});
As per your comment:
Add the javascript before the
<script src="js/test.js"></script>
</body>
</html>
otherwise its not actually part of the DOM and wont get run
As per your second comment
Try putting your code inside a .ready like this. This ensures that the document is completely built before attempting to attach the .submit handler. And stops it attempting to add the handler before there is an object to attach it to in the DOM.
$( document ).ready(function() {
$( '#user-data-form' ).submit( function(event) {
event.preventDefault();
alert( "Handler for .submit() called." );
return false;
});
});
Try this:
In your html:
<input type="submit" class="btn btn-effect-ripple btn-primary" value="Update" id="SUBMIT">
JS:
$('#SUBMIT').on('submit', function(e) {
e.preventDefault();
var confirm = confirm('Message');
if(confirm === true){
//do something
}else{
return false;
}
});
Try changing your input submit to button and make an id. You can delete your id in your form and put that id in class.
<form method="post" class="form-horizontal form-bordered user-data-form">
<button id="submit" type="submit" class="btn btn-effect-ripple btn-primary" value="Update"></button>
OR
<form method="post" class="form-horizontal form-bordered user-data-form">
<input id="submit" type="submit" class="btn btn-effect-ripple btn-primary" value="Update">
Then in your javascript calling the submit button
$('form.user-data-form #submit').click(function(e){
e.preventDefault();
alert( "Handler for .submit() called." );
return false;
});
Hope that helps
I am very new to jQuery and I'm looking for an explanation as to why this code does not seem to work. I think it is something with the "action" not sure. Can someone help me understand my mistake here. thanks
<script src="/jquery.validationEngine.js"></script>
<script>
$("#contact_body").submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
if ($("#contact_body").validationEngine('validate')) {
//Post Data to Node Server
$.post(
$this.attr("action"), // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) { /** code to handle response **/ },
"json" // The format the response should be in
);
//Notify User That the Email Was Sent to the Server & Thanks!
//$('#contactThanksModal').modal('show');
$('#contactModal').modal('hide');
alert("success");
}
else {
//handle Invalid Email Format Error
alert("error");
}
});
</script>
<!--pop up contact form -->
<div id="contact" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>Send us a message</h3>
</div>
<div class="modal-body">
<form id="contact_body"class="contact_body" name="contact_body" action="/contact">
<label class="label" for="form_name">Your Name</label><br>
<input type="text" name="form_name" id="form_name" class="input-xlarge"><br>
<label class="label" for="form_email">Your E-mail</label><br>
<input type="form_email" name="form_email" class="input-xlarge"><br>
<label class="label" for="form_msg">Enter a Message</label><br>
<textarea name="form_msg" class="input-xlarge"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
<!-- <div id="thanks"><p><a data-toggle="modal" href="#contact" class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> -->
You need to wrap your JQuery scripts in a
$(document).ready(function() {
...your_code_here...
});
This will then wait for the whole document to load before trying to attach events to objects.
Without this you may be trying to bind events to objects that have yet to be "created".
You need to put your code in a document ready handler:
<script src="/jquery.validationEngine.js"></script>
<script>
$(function() {
$("#contact_body").submit(function(e) {
// your code...
});
});
</script>
Your code is currently trying to add the submit() handler before the element exists in the DOM.
html:
<input id="save "type="submit" value="Create" class="btn btn-primary"/>
javascript that register onclick (IsValid is a function that validates before submiting, returns true of false)
$('#save').click(function () {
return IsValid();
});
Note that this exact same code works if I write:
<input id="save "type="submit" value="Create" class="btn btn-primary" onclick='javascript: IsValid();'/>
This is another option without modifying the markup (createForm is the form)
$('#createForm').submit(function () {
return IsValid();
});
Why $('').click is not registering my event handler?
Form looks like this:
<form method="post" id="createForm" class="well" action="/ScheduleWorkDay/Create" novalidate="novalidate">
It maybe that your id has a space or you have not used document.ready()
here is the working demo
<input id="save" type="submit" value="Create" class="btn btn-primary"/>
$(document).ready(function(){
$('#save').click(function () {
alert("invalid");
});
});
Demo
MrOBrian was right. The problem was that
<input id="save "
had an extra space in the id name. Thanks!
Your event handler isn't registering because there are no handlers on the form with the id save, but there is a save (with a space). Remove the space.
<input id="save" type="submit" value="Create" class="btn btn-primary"/>
$('#save').click(function () {
return IsValid();
});
should work without issues.
A jsFiddle showing it working