Form submits on keyup after validation, instead of onclick - javascript

Here is a JSFiddle which will show the issue that I am having.
Currently, form data gets submitted on keyup as soon as that data is validated, which it should really only submit data when the 'subscribe' button is clicked.
So the form should work like this. If a user clicks the subscribe button, and a particular input fails validation, then that error should be shown. If the user then corrects the error, that specific error should clear on keyup, however, the user should have to click 'subscribe' before the form actually submits any data, or checks for validation again. Currently, the form submits on keyup after passing validation and that should not be the case.
I want to know how I can validate (not submit data) on keyup, as well as validate on click, in addition to submitting data on click.
http://jsfiddle.net/cqf8guys/5/
Code:
$(document).ready(function() {
$('form #response2').hide();
$('.txt1').on('keyup click', function(e) {
e.preventDefault();
var valid = '';
var required = ' is required';
var first = $('form #first').val();
var last = $('form #last').val();
var city = $('form #city').val();
var email = $('form #email').val();
var tempt = $('form #tempt').val();
var tempt2 = $('form #tempt2').val();
if(first=='' || first.length<=1) {
$('form #first').css('border','2px solid #ff0000');
$('form #first').css('background-color','#ffcece');
valid += '<p>Your first name is required</p>';
}
else {
$('form #first').removeAttr('style');
}
if(last=='' || last.length<=1) {
$('form #last').css('border','2px solid #ff0000');
$('form #last').css('background-color','#ffcece');
valid += '<p>Your last name' + required + '</p>';
}
else {
$(this).removeAttr('style');
}
if(city=='' || city.length<=1) {
$('form #city').css('border','2px solid #ff0000');
$('form #city').css('background-color','#ffcece');
valid += '<p>Please include your city</p>';
}
else {
$('form #city').removeAttr('style');
}
if (!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>A valid E-Mail address is required</p>';
}
if (tempt != 'http://') {
valid += '<p>We can\'t allow spam bots.</p>';
}
if (tempt2 != '') {
valid += '<p>A human user' + required + '</p>';
}
if (valid != '') {
$('form #response2').removeClass().addClass('error2')
.html('' +valid).fadeIn('fast');
}
else {
$('form #response2').removeClass().addClass('processing2').html('<p style="top:0px; left:0px; text-align:center; line-height:1.5em;">Please wait while we process your information...</p>').fadeIn('fast');
var formData = $('form').serialize();
submitFormSubscribe(formData);
}
});
});
function submitFormSubscribe(formData) {
$.ajax({
type: 'POST',
url: 'http://3elementsreview.com/blog/wp-content/themes/3elements/php-signup/sign-up-complete.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 4000,
success: function(data) {
$('form #response2').removeClass().addClass((data.error === true) ? 'error2' : 'success2')
.html(data.msg).fadeIn('fast');
if ($('form #response2').hasClass('success2')) {
setTimeout("$('form #response2').fadeOut('fast')", 6000);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('form #response2').removeClass().addClass('error2')
.html('<p>There was an <strong>' + errorThrown +
'</strong> error due to an <strong>' + textStatus +
'</strong> condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {
$('form')[0].reset();
}
});
};

This is because you have attached your functionality to the wrong event listener type. You don't want $('.txt1').on('keyup click', function(e) {... that's why it is getting mixed up when you deselect something. Instead you want the submit event listener like so....
$('.txt1').on('submit', function(e) {... or $('.txt1').submit(function(e) {...
then if the validation fails you can do an e.preventDefault(); and no form submission will occur.
Here is an example not using your own code...
JAVASCRIPT
var zipSwitch = false;
$(function() {
zipValidate();
validateForm(); //Add Form Submit Validation Event
});
//Constantly Monitor Validation
function zipValidate() {
$("#zip").keyup(function() {
var zipInput = $("#zip").val();
if($.isNumeric(zipInput)) {
$("#msgZone").html("Zip is correct");
$("#msgZone").attr("style", "border-color: rgb(4, 255, 17)");
zipSwitch = true;
} else {
$("#msgZone").html("Zip must be numbers only. Please remove letters.");
$("#msgZone").attr("style", "border-color: rgb(250, 20, 10)");
zipSwitch = false;
}
});
}
//Allow Form To Submit or Not Depending on Validation
function validateForm() {
$("#form1").submit(function(e) {
//If Form Validation Was Correct
if(zipSwitch==true) {
var validCountry = countryValidationFunction();
if(validCountry==true) {
alert("Form Submitted Successfully");
} else if(validCountry==false) {
alert("Please Enter a Valid Country");
e.preventDefault();
}
} else {
e.preventDefault();
}
});
}
HTML
<form name="form1" id="form1" action="#" method="POST" class="span12" style="margin-top: 50px;">
<div id="msgZone" class="well">
Validation Message Zone
</div>
<div class="controls-row">
<span class="help-inline control-list">Zip:</span>
<input id="zip" name="zip" type="text" class="input-medium" required="true" />
</div>
<hr />
<div class="controls-row">
<button type="submit" id="btnSubmit" class="btn btn-success" onSubmit="validateForm()">Submit</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
<hr />
</form>

Related

Validating individual form inputs with javascript

I have a registration form that validates a text field, if it's empty when a user clicks/tabs off which shows an error message. My issue with the below code is its a lot to duplicate across several form fields. The below example is for first name but I can't see a way of using what I have to do the same for more than one field.
/* this will call ajax call after entering all the below three fiels */
var $fields = $('#testid');
$fields.live('blur',function(e) {
e.preventDefault();
var $emptyFields = $fields.filter(function() {
return $.trim(this.value) === "";
});
if ($emptyFields.length) {
var frm = $(this).parents('form');
var url=$('#valNameEmail').val();
jQuery.ajax({
url: url,
data: $(this).parents('form').serialize(),
type: 'POST',
dataType: "json",
success: function(response){
if (response.HtmlMessage === 'success'){
$('.reg-alreadyRegistered').html('');
$('.reg-alreadyRegistered').css('display', 'none');
ACC.registration.tickIcon($('#testid'));
var radioExCustValue = $('#registration-form input[name=existingCustomer]:checked').val();
if (userNameAjax === true) {
if (radioExCustValue == 'false'){
$('#regFormSubmit').removeAttr('disabled');
}
else {
if (customerValidation == true){
$('#regFormSubmit').removeAttr('disabled');
}
}
}
emailIDajax = true;
} else {
ACC.registration.errorIcon($('#testid'));
$('.reg-alreadyRegistered').html(response.HtmlMessage);
$('.reg-alreadyRegistered').css('display', 'block');
emailIDajax = false;
$('#regFormSubmit').attr('disabled','disabled');
}
},
error: function(){
//alert(response);
//console.log('ERROR!')
}
});
}
});
You can give the same inputs that require same sort of validation a class (or if you want it for example for all input[type=text] then you can use it for the selector.
So let's say I have a form like this:
<form id="mform">
<input type="text" class="inptxt" name="it1" />
<input type="text" class="inptxt" name="it2" />
<!-- other similar text inputs with the same class -->
<input type="submit" id="sub" value="Submit" />
</form>
I have a function for text inputs which returns false if the field is empty, otherwise true:
$.fn.isValid = function() {
return $.trim($(this).val());
}
And then I get the inputs by class and validate them all at once:
$('#mform').on('submit', function(e) {
e.preventDefault();
var allValid = true;
$('.inptxt').each(function() {
if (!$(this).isValid()) {
$(this).css('background-color', 'red');
allValid = false;
}
else
$(this).css('background-color', 'white');
});
if(allValid) {
//everything's valid ... submit the form
}
});
jsfiddle DEMO
This worked for me:
$('#registration-form input').blur(function(){
if( $(this).val().length === 0 ) {
ACC.registration.errorIcon($(this));
}
else{
ACC.registration.tickIcon($(this));
}
});
thanks for your help

Prevent page reload on enter key pressed

i have the following input field:
<input type="text" id="txt_comment" class="form-control" placeholder="Skriv kommentar">
with this i have the following code
$('#txt_comment').keyup(function(e){
if(e.keyCode == 13)
{
addComment();
return false;
}
e.preventDefault();
});
However when i press enter it still reloads the page. Can anyone tell me what im doing wrong?
Update
function addComment()
{
var comment = $('#txt_comment').val();
{
$.ajax({
type: 'POST',
url: '/Comment/addComment',
dataType: 'json',
data: {
request: 'ajax',
reciver:user_id,
comment: comment
},
success: function (data)
{
$('#comment_list').prepend(
' <li class="list-group-item animated fadeInRightBig">'+
' <p><b class="text">'+data['sender']+'</b>:'+
'<br/>'+comment+' </p>'+
'<input type="hidden" class="timestamp" value="'+data["timestamp"]+'">'+
' <small class="block text-muted timeSmall"><i class="fa fa-clock-o"></i></small>'+
'</li>'
)
$('.timestamp').each(function()
{
var text = $(this).next()
var timer = $(this).val();
var new_text = moment(timer, "YYYY-MM-DD- HH:m:ss").fromNow();
text.html(new_text);
});
$('#txt_comment').val('');
}
})
}
}
And my function now look like this:
$('#txt_comment').keyup(function(e){
if(e.keyCode === 13)
{
addComment();
e.preventDefault();
return false;
}
});
Still having page reloads
For quick reference: To solve the issue, add a hidden input field to your form.
This is a relic from the an older version of HTML:
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
The return is firing before the preventDefault call, just re-arrange them:
$('#txt_comment').keyup(function(e){
e.preventDefault();
if(e.keyCode === 13) {
addComment();
return false;
}
});
Use the keydown function instead:
$('#txt_comment').keydown(function(e){
if(e.keyCode == 13)
{
addComment();
return false;
}
e.preventDefault(); });

Submit form button stuck after ajax post

Hi i have a form which uses Ajax to make a post in Rails 4. The javascript runs some validation and should return an alert message once the post is successful. Currently the submit button stays depressed and although the form posts no message gets alerted. I dont know what i'm doing wrong and just want the form to alert a message and then reset itself.
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "emailer",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('input#name').reset();
$('input#email').reset();
$('textarea#text').reset();
}
});
return false;
});
You are preventing the wrong event. You need the 'onsubmit' event of the form not the 'onclick' event of the submit button.
$('#myform').on('submit', function(event){
event.preventDefault();
/* your code here */
});
For more info please read :
How to prevent form from being submitted?
First of all the reset function is not for the text boxes..it will run for the form. So the corrected code would be...
<script>
$(function(){
$('#submit1').click(function(e){
e.preventDefault();
var name = $('input#name').val();
if (name == "") {
alert("please enter a name!");
$('input#name').focus();
return false;
}
var email = $('input#email').val();
if (email == ""){
alert("please enter your email");
$('input#email').focus();
return false;
}
var content = $('textarea#text').val();
if (content == ""){
alert("please enter a comment");
$('textarea#text').focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&content=' + content;
$.ajax({
type: "POST",
url: "user_availability.php",
data: dataString,
dataType: 'json',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
success: function(){
alert("mappy jappy");
$('#contact-form')[0].reset();
}
});
return false;
});
});
</script>
AND the html part would be like below-
<form id="contact-form" method="post" enctype="multipart/form-data">
<input type="text" id="email" name="email" />
<input type="text" id="name" name="name" />
<textarea name="text" id="text"></textarea>
<input type="submit" value="submit" id="submit1" />
</form>
Please Check and let me know...

Trigger event on submit

In a newsletter sign-up form, I would like to make the email disappear after the end user hits enter. I have already added JS to hide and unhide the placeholder text.
The code:
<form id="form" action="https://xxxx.com/subscribe/post-json?u=xxx&id=xx&c=?" method="GET">
<input type="hidden" name="u" value="xxx">
<input type="hidden" name="id" value="xxx">
<input id="email" type="EMAIL" autocapitalize="off" autocorrect="off" name="MERGE0" id="MERGE0" size="25" placeholder= "Type your email and press enter">
<p id="response"></p>
</form>
And the JS:
<script >
var text = document.getElementById("email");
text.onfocus = function() {
if ( text.placeholder == "Type your email and press enter") {
text.placeholder = "";
}
};
text.onblur = function() {
if ( text.placeholder == "") {
text.placeholder = "Type your email and press enter";
}
};
</script>
I tried to create a function to trigger the event but it still didn't work:
function checkEnter(event)
{
if (event.keyCode == 13) {text.placeholder = "cool";}
};
Could you all see what's wrong with my code?
Thank you.
You need to add a event listener for the enter key. You could remove your function checkEnter and use this instead:
document.querySelector('#email').addEventListener('keypress', function (e) {
var key = e.which || e.keyCode;
if (key == 13) {
text.placeholder = "cool";
}
};
I have integrated the code below with the mailchimp form and got the desired results:
var paragraph = document.getElementById('response');
$('#form').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "https://xxxxx.com/subscribe/post-json?u=xxxx&id=xxx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
text.placeholder = "Oopsy daisy! Error :-(";
form.reset();
} else {
paragraph.innerHTML = data.msg;
text.placeholder = "Thanks so much!";
form.reset();
}
}
});
return false;
});

Exiting from javascript function not working

I have this javascript function:
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
}
What am hoping this achieves is, if the input field is empty, display the alert and remain in the function.If it isn't then continue.
My submit button is linked to another page but this page is displayed anyways regardless of what happens in the if statement.
This is the form code:
<form id="post" action="http://localhost:8080/uploadNewMessage" method="post">
<fieldset>
<div data-role="fieldcontain">
<label for="msg" class="input">Message:</label>
<input type="text" name="msg" id="msg" size="10"/>
</div>
Submit
</fieldset>
</form>
and the full javascript code just incase:
$(document).ready(function() {
// 1. The Registration button
$("#submit").bind('click', function(event) {
displayMessage();
});
});
function doPostRequest(postData) {
$.ajax({
type: "POST",
url: URL,
dataType: "json",
data: postData
});
}
function displayMessage() {
var message = $("#msg").val();
if (message == "") {
alert("You need to enter a message");//alert the user
return false;
}
postData = {
"message": message,
};
...
doPostRequest(postData);
}
You may try something like this:
$("#submit").bind('click', function(event) {
var message = $.trim($("#msg").val());
if(!message.length) {
alert("You need to enter a message");
return false;
}
else {
event.preventDefault();
doPostRequest({"message":message});
}
});
demo
$(function() {
$("#submit").on('click', function(event) {
event.preventDefault(); // prevent default anchor behavior
displayMessage();
});
});
and also:
function displayMessage() {
var message = $.trim( $("#msg").val() ); // trim whitespaces
if (message === "") {
alert("You need to enter a message");
}else{ // Use the else statement
doPostRequest({
"message" : message
});
}
}
The event variable that is passed via your click event handler contains a function named preventDefault. If you don't want the form to submit, call this (event.preventDefault()). This will prevent the submit button from submitting the form.

Categories

Resources