I am using form validator plugin to validate my forms.
It is working properly if I am not submitting data using jQuery post method.
On using jQuery post it is not validating the form on submit.
My code is
<form action="UpdatedProfile" method="post" name="updateprofile" id="UpdatedProfile" class="form-horizontal">
<div class=" form-group ">
<div class="col-lg-2">
<label>First Name</label>
</div>
<div class="col-lg-4">
<input type="text" name="fname" cssClass="form-control" data-validation="required" data-validation-error-msg="First Name is required"/>
</div>
</div>
</form>
<script>
$(document).ready(function () {
$.validate();
$(document).on('click', '#submit', function (event) {
event.preventDefault();
console.log($('#UpdatedBasicProfile').serialize());
$.post("Updated", $('#UpdatedProfile').serialize(), function (data)
{....});
});
});
</script>
How to achieve this?
put a submit button in the form and define validation rule in js like
$('#frm_registration').validate({
rules:
{
fname: required
},
messages:
{
fname : 'Please enter name'
}
});
or if the button is of type button then initiate validation on its click like:
$('#btn').click(function(){
$('#frm_registration').valid(); // will initiate the validation
})
If the validator is working when clicked on submit button, you could trigger a click event on the button rather then listening the document for any clicks and if the target is the given button.
Related
I am working on a website for my app development class and I have the weirdest issue.
I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submitting the form, and I cannot or the life of me figure out how to make the JQuery go on in just the background. That is sorta of the point of using JQuery in the first place haha. Anyways, I will submit all relevant code, let me know if you need anything else.
<script type="text/JavaScript">
$(document).ready(function () {
$('#button').click(function () {
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
</script>
<div class= "main col-xs-9 well">
<h2 style="color: black" class="featurette-heading">Join our mailing list!</h2>
<form id="main" method = "post" class="form-inline">
<label for="inlineFormInput">Name</label>
<input type="text" id="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<label for="inlineFormInputGroup">Email</label>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<input type="text" id="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe#email.com">
</div>
<!--Plan to write success message here -->
<label id="success_message"style="color: darkred"></label>
<button id ="button" type="submit" value="send" class="btn btn-primary">Submit</button>
</form>
This is my php if its relevant:
<?php
include 'connection.php';
$Name = $_POST['name'];
$Email = $_POST['email'];
//Send Scores from Player 1 to Database
$save1 = "INSERT INTO `contact_list` (`name`, `email`) VALUES ('$Name', '$Email')";
$success = $mysqli->query($save1);
if (!$success) {
die("Couldn't enter data: ".$mysqli->error);
echo "unsuccessfully";
}
echo "successfully";
?>
This is a screenshot of the log:
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
Use <button type="button"> to override default submission behavior
Use event.preventDefault() in the onSubmit event to prevent form submission
Solution 1:
Advantage: simple change to markup
Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?
Insert extra type attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Solution 2:
Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Better variant:
In this improvement, we listen to the submit event emitted from the <form> element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:
The name attribute is required for .serialize() to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe#email.com">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
clear the previous state when loading the page.... add this to document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
I am creating a comment functionality and below are my code so far.
html
<form action="http://website.com/transaction_items/add_comment" class="" id="form-comment" role="form" method="post" accept-charset="utf-8">
<input type="hidden" name="checklists_item_id" value="6" style="display:none;">
<input type="hidden" name="user_id" value="1" style="display:none;">
<div class="input-group col-xs-12">
<input type="text" name="comment" value="" class="form-control" id="comment-input" placeholder="Enter your comments..">
<span class="input-group-btn">
<button class="btn btn-default" id="doc-comment" type="button">Post</button>
</span>
</div>
</form>
jQuery
This function is called when document is ready.
function comment () {
$('#doc-comment').click(function (e) {
var form_id = '#' + $(this).parents('form').attr('id');
// submit data from the form
submit.send(form_id);
});
}
The problem:
Using the button <button class="btn btn-default" id="doc-comment" type="button">Post</button> to submit data work fine, but
if I use enter in the keyboard, submit.send(form_id); will not do its function, instead the default form submission will execute.
How can I use ajax if use enter in the keyboard to submit form data?
nutshell
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// do your ajax stuff here
});
you can then toss the onclick button listener.. as this will handle the button submit as well
There are more ways to submit a form then simply pressing the submit button.
You need to:
Use the forms submit method
Keep the form from doing the full submit.
-
// This will catch the *enter* as well as the submit button
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// You can then submit the form via ajax and update things as needed.
});
IF you are going to use a button you should at least do a
<button type="button">...</button>
which behaves differently.
$("#form-comment").keyup(function (e) { // On pressing enter
if (e.keyCode == 13) {
// put your ajax code here
}
});
You may have to disable the default Enter event for the form submit button as well depending on your browser.
So in the Jquery Button click function make sure you have something like
event.preventDefault();
I am trying to validate a bootstrap form with jQuery.
var formSubmit = $("#dl-mg-form-publish").validate({
rules: {
'dl-mg-input-youtube': {
required: true,
url:true,
},
'dl-mg-input-title': {
required: true,
minlength: 6 });
I am trying to validate this:
var videoInformation = {
youtubeID: $('#dl-mg-input-youtube').val(),
title: $('#dl-mg-input-title').val(), }
This is my html:
<form class="form-horizontal dl-mg-form-horizontal" id="dl-mg-form-publish" action="#">
<div class="form-group">
<label for="dl-mg-input-youtube" class="control-label col-xs-2">YouTube Video ID:</label>
<div class="col-xs-6">
<input type="url" class="form-control" id="dl-mg-input-youtube" name="dl-mg-input-youtube" placeholder="Youtube ID">
</div>
</div>
<div class="form-group">
<label for="dl-mg-input-title" class="control-label col-xs-2">Video Title:</label>
<div class="col-xs-6">
<input type="text" class="form-control" id="dl-mg-input-title" name="dl-mg-input-title" placeholder="Video Title">
</div>
</div>
I am new at programming I don't know how to validate first and then submit. I tried using a .click handler but it submits the fields with errors anyway. Please help!
Before submitting your form you need to validate the form. You can do this inside the click event like:
$("#target").click(function () {
// Validate the form first
if (!$("#dl-mg-form-publish").valid()) return false;
// Your form is valid, so continue with you submit logic..
});
More info here: .valid()
EDIT:
Disable auto validation on keypress
Use this options for the validate() method:
$("#dl-mg-form-publish").validate({
onfocusout: false,
onkeyup: false,
// other options here
})
My website has a simple form that is linked with MailChimp. The problem is that the form's submit button has conflicting interests, specifically, there's javascript email-field validation code that
is requiring the button to have type="submit" written in the button code. But if I include type=submit, it prevents my form from submitting to MailChimp.
Here is the button code in 2 forms. The first is the form which allows javascript error validation to work but submission to MailChimp to NOT work (notice the type)
<button class='buttonmain' type="submit" >Submit Form</button>
The second form does not have type="submit" and so js validation won't work, but it will submit to MailChimp:
<button class='buttonmain'>Submit Form</button>
Here's the full form
<form id="form-signup_v1"
name="form-signup_v1"
method="POST"
action="http://mysite.us10.list-manage.com/subscribe/post"
>
<!-- MailChimp Code -->
<input type="hidden" name="u" value="g02362223cdaf329adf5">
<input type="hidden" name="id" value="32da65235dba0">
<div class="errorstyle">
<div class="field">
<div class="ui left labeled input">
<input id="MERGE0"
name="MERGE0"
placeholder="My Email Address"
type="text"
data-validation="[EMAIL]">
<div class="ui corner label">
<i class="asterisk icon">*</i>
</div>
</div>
</div>
</div>
<button class='buttonmain' type="submit" >Submit</button>
</form>
and here's the script for validating the e-mail field.
Notice how it calls on "submit".
<script>
$('#form-signup_v1').validate({
submit: {
settings: {
inputContainer: '.field'
},
callback: {
onBeforeSubmit: function (node) {
myBeforeSubmitFunction(':D', ':)', node);
},
onSubmit: function (node) {
console.log('#' + node.id + ' has a submit override.');
//node.submit();
}
}
},
debug: true
});
function myBeforeSubmitFunction(a, b, node) {
console.log(a, b);
$(node).find('input:not([type="submit"]), select, textarea').attr('readonly', 'true');
$(node).append('<div class="ui active loader"></div>');
}
$('#prefill-signup_v1').on('click', function () {
var form = $(this).closest('form');
form.find('#signup_v1-name').val('John Doe');
form.find('#signup_v1-username').val('RocketJoe');
form.find('#signup_v1-password').val('test123');
form.find('#signup_v1-password-confirm').val('test123');
form.find('#signup_v1-email').val('test#test.test');
form.find('#signup_v1-email-confirm').val('test#test.test');
});
</script>
How do I combine the 2 button code forms I posted at the beginning, so that the form IS validated with js and also submits to MC?
Thanks so much!
I solved it myself doing the following:
Changing the script to include:
function myBeforeSubmitFunction(a, b, node) {
document.getElementById("form-signup_v1").submit();
I've downloaded a bootstrap template which has 1 email form in it. I'm trying to add a second form with other fields on the same page. When I click the submit button in my second form, the values of the original form are always used.
Here is my html:
// second form added by me
<form name="sentMessage2" id="contactForm2" novalidate>
// input elements like for example #name
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success">Send</button>
</div>
</div>
</form>
// original form
<form name="sentMessage" id="contactForm" novalidate>
// input elements like for example #name
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success">Send</button>
</div>
</div>
</form>
And here is my javascript file contact_me.js (not adjusted):
$(function() {
$("input,textarea").jqBootstrapValidation({
// I dont understand how the form calls this method. There is no reference to the form's name/id
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#emaill").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name;
// when I debug here, I always see the values from the original form
How can I create a second form that sends an email?
Change the id properties on your second form and the jquery selectors. Eg. rename 'email' to 'email1', and such, as you did with the form.
A better solution would be to stop using id-s at all, and switch to "name" attributes.
Set id and class for each button
// second form added by me
<form name="sentMessage2" id="contactForm2" novalidate>
// input elements like for example #name
<div class="row">
<div class="form-group col-xs-12">
<button id"btn2" type="submit" class="btnSend btn btn-success">Send</button>
</div>
</div>
</form>
// original form
<form name="sentMessage" id="contactForm" novalidate>
// input elements like for example #name
<div class="row">
<div class="form-group col-xs-12">
<button id"btn1" type="submit" class="btnSend btn btn-success">Send</button>
</div>
</div>
</form>
Your jquery code will be like this
$( document ).ready(function() {
$(".btnSend ").click(function() {
var id = $(this).attr("id");
if(id==="btn1"){
$( "#contactForm" ).submit();
}
if(id==="btn2"){
$( "#contactForm2" ).submit();
}
});
});
I didnt test but it should work.