jQuery submit a form - javascript

html code
<div id="signup">
<form id="suform" method="POST" action="roma/roma">
<p>
<label>Frist Name</label>
<input type="text" id="sufName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Last Name</label>
<input type="text" id="sulName"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" id="suEmail"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Mobile Number</label>
<input type="text" id="suMNumber"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" id="suPassword"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Re Password</label>
<input type="password" id="suRePassword"/>
<span class="errorMessage"></span>
</p>
<p>
<input type="submit" class="button" value="sign up"/>
</p>
</form>
</div>
it is just six input fields to make a sign up page
and this is the jQuery code to ensure that there is no input field empty, and if there is no input field empty I want to submit the form.
jQuery code
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
$(this).submit(); // submit form if no error
}
});
});
The code ensure that there is no input field empty, it found an empty one then an error message will appear, else should submit, but the submit doesn't work.
code

Try using $(this)[0].submit();. Using $(this) refers to the jQuery object reference to the form. I don't know what jQuery's submit() method actually does, but it clearly doesn't submit the form. Using $(this)[0] refers to the actual DOM element, which will use the standard DOM submit method, which is what you're looking for.
I'm sure you know this already, but you should use server and client side validation, because some users don't have JS and some users will purposely tamper with your form. Just a quick "Don't forget"!

Check out the jQuery validation plugin. For this you add a class = "required" for any input field that is required, and just call validation on it:
$('form').validation({
// any options you want
});
It will also do handy things like displaying error messages, doing conditional validation, etc.

You can remove e.preventDefault() and use return insead:
$('form').on('submit', function(e){
var errorCount = 0;
$('span.errorMessage').text('');
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text();
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
return errorCount === 0;
});
DEMO: http://jsfiddle.net/h9njC/27/

$('form').on('submit',function(e){
var errorCount = 0;
$('span.errorMessage').text('');
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text();
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
alert('done'); // just an alert to notice when everything OK [remove it]
$this.submit(); // submit the form on success
} else e.preventDefault(); // halt the submission on default
});
DEMO

Related

Validate only visible fields in a form

I am validating one form. when required fields are not entered it will return alert.its working fine.
Now I have hide some form fields by adding ng-class,when I click submit I don't want to validate hidden fields I want to validate only those fields which are not having hidden class.
These are my inputs:
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.name" />
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.id"/>
</section>
<section>
<input class="required" type="text" ng-model='currentData.age'/>
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model='currentData.gender'/>
</section>
<section>
<input class="required" ng-model='currentData.description'/>
</section>
Here am validating my fields :
$form.find('input.required').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
I have added `:visible` its working good.But that wont be a proper solution I guess.Because if there are multiple tabs which is not having `hidden class`means, it will validate only current tab user currently viewing.
$form.find('input.required:visible').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
Any other suggestions?
$('form').find('input.required').parent('*:not(".hidden")').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
assuming $('form') is <form></form>,
otherwise it should be something like
$('#form') for <div id="form"></div>
Got solution:
$form.find('section').not(".hidden").closest('input.required').each(function() {})
I just changed my elements order.

How to prevent form from submiting until the neccesary fields are fiiled

I have a questionaire website, that has about 30 qustions, the website is such that it, displays one question at a time.You only go to the next question when you press the next button.
I have a problem, when I click the next button, the form automatically sends submits the form to the php_script, which then submits the data to the database,
Below is the jquery file that enbales the form to show one question at a time. But the problem is when the next button(which is within the form element) is clicked, the form submits, even when the other mandatory fields are empty.
On the database I end up having the first response and the rest are null or zeros
I would greatly appreciate your efforts in helping me.I do not know what to do now
var q = 1;
$(document).ready(function() {
var selectedOption = $('input[name=options]:checked').val();
$(".questions").hide();
$("#question1").show();
$("#next").click(function() {
$("#question" + q).hide();
q = q + 1;
if(q > 30) {
$("#next").remove();
$("body").append("<input type='submit' value='Submit'>");
} else {
$("#question" + q).show();
}
});
if ((selectedOption == '')){
e.preventDefault();
}
});
Your current validation code is within:
$(document).ready(...)
Which executes at soon as the browser has parsed all the HTML. That is not the correct time to validate form elements.
You need to have this logic in your <form> element's submit event so that you can validate the form elements at the right time and then your e.preventDefault() will potentially cancel the submit event.
Additionally, don't set variables equal to the value of a property of your HTML elements, as you are doing with this line:
var selectedOption = $('input[name=options]:checked').val();
Because this will store just the value of the element at that moment in time. When the value changes later, your variable won't have that data.
Even if you had these things correct, your actual event cancellation code of:
e.preventDefault();
Wouldn't work because you have not captured the event object reference as an event handling function argument. e would be undefined.
This is more of the structure you should be using (see comments inline for details):
var q = 1;
$(document).ready(function() {
$(".questions").hide();
$("#question1").show();
$("#next").click(function() {
$("#question" + q).hide();
q++;
if(q > 30) {
$("#next").remove();
$("body").append("<input type='submit' value='Submit'>");
} else {
$("#question" + q).show();
}
});
// Set up the form's submit event handler. If you want to access the
// event within that function, you need to set up the function to
// bind the event to an event argument (e in this case).
$(form).on("submit", function(e){
var selectedOption = $('input[name=options]:checked');
// Do your validation
if ((selectedOption.val() == '')){
e.preventDefault(); // Cancel the current event
e.stopPropagation(); // Stop the current event from propagating
}
});
});
I re-invented the wheel a bit, the original code was a bit vague on the html aspect, so I splurged and wrote how I would accomplish something similar with heavy reliance on jQuery and event handlers. Also no submit buttons, handle that with jQuery.
Index.html
$(function() {
// Namespace to not pollute, be good to your browser environment, but still allow access from the outside
window.QUESTIONS = window.QUESTIONS || {};
// Save references, because it's not my memory, but my time
QUESTIONS.form = $('#questionForm')
// Disable everything from the start
QUESTIONS.next = $('#next').prop('disabled', true);
QUESTIONS.previous = $('#previous').prop('disabled', true);
QUESTIONS.complete = $('#complete').prop('disabled', true);
// We start at 1
QUESTIONS.position = 1;
QUESTIONS.max = 3; // Could compute this with jquery, but this is an example
QUESTIONS.current = undefined; // The current question jquery reference
// Never auto submit, but we have a way around this ;)
QUESTIONS.form.submit (function() {
return false;
});
// Hide everything
$(".question", QUESTIONS.form).hide();
function checkButtons() {
var checked = QUESTIONS.current && $('input[type=radio]:checked', QUESTIONS.current).length == 1;
// Complete
if (checked && QUESTIONS.position == QUESTIONS.max) { // Only check if set
QUESTIONS.complete.prop('disabled', false);
} else {
QUESTIONS.complete.prop('disabled', true);
}
// Next
if (checked && QUESTIONS.position < QUESTIONS.max) { // Only check if set
QUESTIONS.next.prop('disabled', false);
} else {
QUESTIONS.next.prop('disabled', true);
}
}
function activateQuestion(position) {
// Hide the old question
if (QUESTIONS.current) {
QUESTIONS.current.hide();
}
// Save the position
QUESTIONS.position = position - 0;
// Save the reference
QUESTIONS.current = $('.question[questionIndex=' + QUESTIONS.position + ']', QUESTIONS.form).show();
// Can we go back?
QUESTIONS.previous.prop('disabled', !(QUESTIONS.position > 1));
// setup buttons
checkButtons();
}
QUESTIONS.form.on('click', 'input[type=radio]', function(){
// When I check something, work on buttons
checkButtons();
});
// Stop enter from submitting
$('.question input[type=radio]', QUESTIONS.form).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
}
});
// Next event
QUESTIONS.next.click(function() {
activateQuestion(QUESTIONS.position + 1)
});
// Previous event
QUESTIONS.previous.click(function() {
activateQuestion(QUESTIONS.position - 1)
});
QUESTIONS.complete.click(function(){
QUESTIONS.form[0].submit();
});
// Show the first
activateQuestion(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="somewhere.php" id="questionForm" method="POST">
<div class="questions">
<div class="question" questionIndex="1">
<h1>Question Title 1</h1>
<p>
<input type="radio" name="question1" id="question1_1" value="A"/> <label for="question1_1">Answer A</label>
</p>
<p>
<input type="radio" name="question1" id="question1_2" value="B"/> <label for="question1_2">Answer B</label>
</p>
<p>
<input type="radio" name="question1" id="question1_3" value="C"/> <label for="question1_3">Answer C</label>
</p>
</div>
<div class="question" questionIndex="2">
<h1>Question Title 2</h1>
<p>
<input type="radio" name="question2" id="question2_1" value="A"/> <label for="question2_1">Answer A</label>
</p>
<p>
<input type="radio" name="question2" id="question2_2" value="B"/> <label for="question2_2">Answer B</label>
</p>
<p>
<input type="radio" name="question2" id="question2_3" value="C"/> <label for="question2_3">Answer C</label>
</p>
</div>
<div class="question" questionIndex="3">
<h1>Question Title 3</h1>
<p>
<input type="radio" name="question3" id="question3_1" value="A"/> <label for="question3_1">Answer A</label>
</p>
<p>
<input type="radio" name="question3" id="question3_2" value="B"/> <label for="question3_2">Answer B</label>
</p>
<p>
<input type="radio" name="question3" id="question3_3" value="C"/> <label for="question3_3">Answer C</label>
</p>
</div>
<button id="previous">Previous</button>
<button id="next">Next</button>
<button id="complete">Complete</button>
</div>
</form>
EDIT 3:
Modified example to hide previous question so only one question at a time is being shown.
EDIT 2:
As pointed out by Scott Marcus I'll move the event handlers inside .ready
Moved the .next button handler outside the .document.ready handler and also added a .submit form handler so you can handle the form submission right there.
This will help you have a single point of code to manage all your form submission situations (validations, messages, clean up, etc.)
$("[id^='question']").each(function(i){
In the previouse line of code we are checking every question that starts with the name question (it matches question1, question2, question3, question11, questionXX, etc.) and for each one of them we test their value (text entered by the user, if ANY of those questions is empty you will prevent the form submission with e.preventDefault(); if everything is correct you just let them submit the form.
var q = 1;
$(document).ready(function() {
$("[id^='question']").hide();
$("#question1").show();
$("#next").click(function() {
$("#question" + q).show();
q = q + 1;
if(q > 4) {
$("#question" + (q-1)).hide();
$("#question" + q).show();
$("#next").remove();
$("#f1").append("<input type='submit' value='Submit'>");
} else {
$("#question" + q).show();
$("#question" + (q-1)).hide();
}
});
$('#f1').submit(function(e){
//var selectedOption = $('input[name=options]:checked').val();
//if ((selectedOption == '')){
// e.preventDefault();
//}
// Check that all 5 inputs have text
$("[id^='question']").each(function(i){
if($(this).val() == ''){
alert('Question ' + $(this).prop('id') + ' is empty!');
e.preventDefault();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="f1">
<div class="questions">
<input type="text" id="question1" />
<input type="text" id="question2" />
<input type="text" id="question3" />
<input type="text" id="question4" />
<input type="text" id="question5" />
<!--
<input type="text" id="question6" />
<input type="text" id="question7" />
<input type="text" id="question8" />
<input type="text" id="question9" />
<input type="text" id="question10" />
-->
</div>
<input type="button" id="next" value="Next" />
</form>
Hope it helps!

javascript ajax post form function and validation

This is my code so far:
$(function () {
$('.contact-form').submit(function (event) {
$(this).find("input , textarea").each(function () {
var input = $(this);
if (input.val() == "") {
event.preventDefault();
$("label, p").addClass("error");
input.addClass("error").one("keydown", function () {
$("label").removeClass("error");
self.removeClass("error");
});
}
});
});
});
What it does:
It prevents the form from redirecting to the php script, it turns all fields red (the error class) if they are not filled, and gives the labels an error class.
What I need help with:
Fix so if one field is getting filled remove the error class as it doesn't right now.
Fix so that the label error class gets removed on the specific field when filled (right now it removes the class on all labels over all fields)
And run this code when every field / textarea is validated to be filled:
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function () {
// Optionally alert the user of success here...
console.log("jag lyckades!");
}).fail(function () {
// Optionally alert the user of an error here...
console.log("jag lyckades INTE");
});
event.preventDefault(); // Prevent the form from submitting via the browser.
My html:
<form class="contact-form" action="<?= path(" postform.php "); ?>" method="post" validate>
<div class="row">
<div class="col-sm-6">
<label for="firstname">Förnamn*</label>
<input type="text" class="required" name="firstname" />
</div>
<div class="col-sm-6">
<label for="lastname">Efternamn</label>
<input type="text" name="lastname" />
</div>
</div>
<div class="row">
<div class="col-sm-6">
<label for="email">E-post*</label>
<input type="text" name="email" />
</div>
<div class="col-sm-6">
<label for="number">Telefon*</label>
<input type="text" name="number" />
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="message">Meddelande*</label>
<textarea name="message"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>Fält markerade med * är obligatoriska</p>
<input class="btn-form" type="submit" value="Skicka">
</div>
</div>
</form>
Thanks... I really appreciate your time guys
EDIT:
This is my code at the moment:
http://jsfiddle.net/dmyhd90d/
My problems now:
Having the ajax call run when there's no more form errors ( it runs even if none is filled now )
The label error class is getting the error class removed now instantly when you fill the fields, but the fields stay error classed till I hit the send button, then it revalidates.
Lets post it all in one place because comments are not the place for this anymore
First:
with form submissions, you can often let the error field just clear when you re-validate so by adding
$('.contact-form').submit(function (event) {
$('.error').removeClass("error"); // This
you can clear the errors out and re-validate the whole form from scratch.
second, you're trying to bind an event so that when you edit the input it clear the error from that input and it's label but right now you're clearing all labels errors so you can change it like this
if (input.val() == "") {
event.preventDefault();
$("label, p").addClass("error");
input.addClass("error").one("keydown", function () {
// $("label").removeClass("error");
$("label[for='" + $(this).attr('name') + "']").removeClass("error"); // becomes this
self.removeClass("error");
});
}
To associate the input you're looking at, with it's label. BTW just so you know it's good to put input id="something" and label for="something" as that'll link the label to the input in html, when you click the label. Remember to keep your names for submitting though.
Additionally I think that
$("label, p").addClass("error");
will add an error to all your labels at once. You might want to change it also to add errors only to the fields that have errors
$("label[for='" + $(this).attr('name') + "'], p").addClass("error");
Edit to answer the comment
$('.contact-form').submit(function (event) {
$('.error').removeClass("error"); // This
$(this).find("input , textarea").each(function () {
var input = $(this);
if (input.val() == "") {
event.preventDefault();
$("label[for='" + $(this).attr('name') + "'], p").addClass("error");
input.addClass("error").one("keydown", function () {
$("label[for='" + $(this).attr('name') + "']").removeClass("error");
self.removeClass("error");
});
}
});
if ($(".errors").length <= 0) { // If there are no more error classes
// Do $.ajax() here
// http://api.jquery.com/jquery.ajax/ <- you need to read this and other similar SO posts about ajax
}
});

Can't use JQuery form validation with two buttons html form

HTML:
<form id="myForm">
<fieldset>
<ol>
<li>
<label for="data">Data</label>
<input id="data" name="data" type="text" placeholder="Ex.º: 14-02-2014" required>
</li>
<li>
<label for="conta">Conta</label>
<input id="conta" type="text" name="conta" placeholder="Ex.º: " required>
</li>
</ol>
<input id="oknovo" type="submit" value="OK & Novo" />
<input id="okfechar" type="submit" value="OK & Fechar" />
</fieldset>
</form>
JS:
$(document).ready(function () {
var form = $('#myForm');
var botao;
form.validate();
if (form.valid()) {
$("#myForm input[type=submit]").click(function (event) {
botao = $(this).attr('id');
alert("clique " + botao);
});
};
});
I want to validate the form using JQuery validation plugin.
If it is valid according to the rules specified in the HTML form, then identify which of the buttons was clicked. The validation plugin is working but the form is never valid, therefore the function is never called to alert the id of the button.
You may see a live JSFiddle here.
If the form isn't valid at DOM ready (which it will never be), then your code to add the event handler to the button won't run. You should consider running your validation on a different event, say when the text in the textbox changes.
Example:
$('input[type=textbox]').change(function() {
// put your validation code here.
});
Put your validation inside the click event, and it starts working:
$(document).ready(function () {
var form = $('#myForm');
var botao;
form.validate();
$("#myForm input[type=submit]").click(function (event) {
if (form.valid()) {
botao = $(this).attr('id');
alert("clique " + botao);
}
event.preventDefault();
});
});
Working fiddle
Try adding event.preventDefault();
$("#myForm input[type=submit]").click(function (event) {
event.preventDefault();
botao = $(this).attr('id');
alert("clique " + botao);
});

Error Message will not show in JQuery if it is NOT the first one encountered

I have a feedback form and I am replicating some code to check for values in text inputs and textareas. I have a name field and a feedback field. The errors hide on document load and at the start of a click function The name one shows as expected, but I cannot get the feedback one to show.
I set the errors to show on document load but hide onclick and I could get the feedback error to show if I filled in the name(the name error would hide, as expected).
HTML form.
<div class="slide-out-div">
<h3>Give us Feedback</h3>
<a class="handle" href="#">Content</a>
<p>We would love to hear your ideas to make the site more user-friendly or efficient for your benefit.</p>
<form name="feedbackform" id="feedbackform" action="" method="post">
<label for="feedname">Name:</label>
<input type="text" name="feedname" id="feedname" style="width:100%" /><br />
<label class="error" for="feedname" id="feedname_error">Please insert your name.</label> <br />
<label for="feedback">Feedback:</label><br />
<textarea name="feedback" id="feedback" style="width:100%;height:150px;"></textarea>
<label class="error" for="feedback" id="feedback_error">Please insert your some feedback.</label> <br />
<input type="submit" value="Submit Feedback" id="feedbacksubmit" />
</form>
<div id="feedwrap"></div>
</div>
JQuery Process
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
return false;
}
Var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
return false;
}
//process
return false;
});
Any help would be greatly appreciated.
It's becasue you are returning false as soon as you complete the validation of the name. That'll stop the execution of the function there and the second error message will not show up. May be you can write something like this.
$('#feedbacksubmit').click(function (e) {
$('.error').hide();
//Cancel the link behavior
e.preventDefault();
var returnvalue = true;
var name = $("input#feedname").val();
if(name == ""){
$("label#feedname_error").show();
$("input#feedname").focus();
returnvalue = false;
}
var feedback = $("textarea#feedback").val();
if(feedback == ""){
$("label#feedback_error").show();
$("textarea#feedback").focus();
returnvalue = false;
}
//process
return returnvalue ;
});
It appears that if I move the error above the textarea is shows but otherwise it does not, it must show but not visible to the user.

Categories