I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>
Related
I'm finding a strange behaviour in a popup FORM when I click on a BUTTON (that operates on some object using a JS code), and on a INPUT (used for submit): in both cases, the form closes, and it is an unexpected action.
Probably is due to something very easy and common that I'm not fixing, but i can't find it.
This is the HTML interested part:
<form name="contactform" id="contactform" class="contact-form">
<div class="contactform-container">
<div class="common">
<label for="name">Nome</label>
<input type="text" id="name" name="name" />
</div>
<div class="common">
<label for="name">Cognome</label>
<input type="text" id="familyName" name="familyName" />
</div>
<div class="common">
<label for="email">e-mail</label>
<input type="text" id="email" name="email" />
</div>
<div class="message">
<label for="message">Annotazioni</label>
<textarea name="message" id="message" class="message"></textarea>
</div>
<div class="passRow">
<fieldset class="validatePass">
<div class="formGroup">
<label class="formLabel"for="password">Password
<span class="passErr"></span>
</label>
<div class="passWrapper">
<input type="password"
id="password"
class="form-control input-md"
name="password"
placeholder="Enter your password">
<span class="showPass">
<i class="fas fa-eye-slash"></i>
</span>
</div>
<p class="progress">Livello di sicurezza</p>
<div id="progressBar">
<div></div>
</div>
<ul id="progressList">
<li>Un carattere minuscolo e uno maiuscolo</li>
<li>Un numero</li>
<li>Un carattere speciale tra "!,%,&,#,#,$,^,*,?,_,-"</li>
<li>Lunghezza minima: 8 caratteri</li>
</ul>
</div>
</fieldset>
</div>
<div class="securityCaptcha">
<p>Inserire il codice nei riquadri sottostanti</p>
<div class="first row">
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck">
<canvas class="valiCaptcha"></canvas>
</div>
<div class="refCheck last">
<canvas class="valiCaptcha"></canvas>
<button class="reloadButton">
<i class="fas fa-redo"></i>
</button>
</div>
</div>
<div class="second row">
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
<div class="refCheck">
<input type="text" name="" maxlength="1">
</div>
</div>
</div>
<div class="contactArea">
<p>Compilare tutti i dati per la prenotazione.</p>
<input type="submit" name="submit" id="submit" value="send">
</div>
</div>
</form>
</div>
The BUTTON that create problem is the one with class reloadButton.
The INPUT is the one with id submit.
I think css aren't necessary.
Regarding the JS part:
let formEls = formPopup.querySelectorAll('.common, .message, .note');
let charCode = [];
const refreshButton = document.querySelectorAll('.reloadButton')[0];
const passInput = document.getElementById('password');
window.onload = function () {
document.querySelector('#reserveBtn').addEventListener('click', function () {
formPopup.classList.add('active');
});
getCode();
formPopup.querySelector('.closeButton').addEventListener('click', function () {
cleanForm();
formPopup.classList.remove('active');
});
formPopup.addEventListener('click', function (ev) {
if (ev.target.id == 'contactform-bg') {
cleanForm();
formPopup.classList.remove('active');
}
});
refreshButton.addEventListener('click', function (ev) {
charCode = [];
getCode();
});
passInput.addEventListener('keyup', function () {
passVal = passInput.value;
checkPass(passVal);
});
};
let cleanForm = function () {
formEls.forEach((item, i) => {
item.classList.remove('typing');
});
// console.log(window['contactform-bg'].innerHTML);
// console.log(document.getElementById('contactform').innerHTML);
// console.log(document.contactform.innerHTML);
document.contactform.name.value = '';
document.contactform.familyName.value = '';
document.contactform.email.value = '';
document.contactform.message.value = '';
passInput.value = '';
};
function getCode() {
let sChars = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,!,#,#,$,%,^,&,*,(,)';
let arrayChars = sChars.split(',');
for (var i = 0; i <= 3; i++) {
// trova un indice casuale tra 0 e la lunghezza dell'array
RefIndex = Math.floor(Math.random() * arrayChars.length);
// assegna il carattere estratto dall'array (strana indicazione del font come giapponese(??)
let char = arrayChars[RefIndex];
charCode[i] = char.toLowerCase;
createImgCaptcha(char, i);
}
}
I avoid to add the createImgCaptcha function because it just create CANVAS and doesn't have any impact on the matter.
Is there anyone able to explain to me why the FORM closes? I tried following the steps in JS but found no errors.
Thanks in advance.
Ok, I found the problems and fixed them.
There were little mistakes one different from another. So, I list them:
The "FORM close object": there was a missing '#' characer in the ref attribute, so I changed the HTML from to , adding also the type attribute for greater completeness.
The "class reloadButton": I finally read that a <button>Click to do something</button> is a default submit button. I didn't know... so, I just added the right type attribute to solve, in this way: <button class="reloadButton" type="button">.
The "submit button": in this case, I changed the prevent JS command: function stopEvent(event) { event.preventDefault();}.
Now, everything works correctly. Sorry if I bored you with these silly things; either way, it's always best to learn from mistakes.
I want to make validation for my input text form, that user cannot go further unless all input forms will be completed. i want to make it through every input that even if first is completed, user needs to complete another 2 etc. but at this moment i am only able to make it through the first one and have no idea how to iterate it through every input text.
My html:
<div class="write-to-us">
<div class="col-md-12 field">
<p>Write to us</p>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Name</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your Name</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Surname</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your surname</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label">Question</label>
<textarea type="text" name="subject" class="my-text-input"></textarea>
</div>
</div>
<div>
<button class="my-button">Check it</button>
</div>
</div>
And my js code for iteration:
myFunction: function() {
var $formField = $('.write-to-us');
if (!$formField.exists()) {
return;
}
initValidation();
function initValidation() {
var errorMsg = $formField.find('.label-error');
var button = $formField.find('.my-button');
var input = $formField.find('input');
var inputContainer = $formField.find('.my-form')
button.click(function(event) {
if(!input.val().trim()) {
errorMsg.css('visibility', 'visible');
inputContainer.addClass('error');
event.preventDefault();
}
});
},
I guess that problem is with .find and should be some jQuery .each but i have no idea how to change it.
I would try doing something like this rather than find.
function initValidation() {
$('.my-button').click(function(){
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my-form').addClass('error');
}
});
});
}
I would like to use jquery.dynamiclist library in my procject.
In the demo page that's running smoothly there is a jquery library in version 1.8.2.
In my project I use version 1.11.1 and this makes dynamiclist plugin doesn't work.
With newer version when I process form I get data with names of inputs but without values (I get 'undefined').
Here is the code from demo.
What I have to change to make it run with newer version of jquery?
<form class="form-horizontal">
<h2>Example 1: Basic List</h2>
<div class="control-group">
<label class="control-label">Party</label>
<div class="controls">
<input name="partyName" type="text" placeholder="Party Name">
</div>
</div>
<div class="control-group">
<label class="control-label">Guest List</label>
<div id="example1" class="controls">
<div class="list-item">
<input name="guestList[0].name" type="text" placeholder="Guest Name">
<i class="icon-minus"></i> Remove Guest
</div>
<i class="icon-plus"></i> Add Guest
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary btn-large" value="Process Example 1"/>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://github.com/ikelin/jquery.dynamiclist/blob/master/jquery.dynamiclist.min.js"></script>
<script>
(function($) {
$(document).ready(function() {
$("#example1").dynamiclist();
// display form submit data
$("form").submit(function(event) {
event.preventDefault();
var data = "";
$(this).find("input, select").each(function() {
var element = $(this);
if (element.attr("type") != "submit") {
data += element.attr("name");
data += "="
data += element.attr("value");
data += "; "
}
});
alert(data);
location.reload(true);
});
});
})(jQuery);
</script>
Simply change element.attr("value"); to element.val();.
Sorry I had to include the plugin code manually because apparently you cannot include the src directly from github. Also commented the reload for the snippet.
<form class="form-horizontal">
<h2>Example 1: Basic List</h2>
<div class="control-group">
<label class="control-label">Party</label>
<div class="controls">
<input name="partyName" type="text" placeholder="Party Name">
</div>
</div>
<div class="control-group">
<label class="control-label">Guest List</label>
<div id="example1" class="controls">
<div class="list-item">
<input name="guestList[0].name" type="text" placeholder="Guest Name">
<i class="icon-minus"></i> Remove Guest
</div>
<i class="icon-plus"></i> Add Guest
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary btn-large" value="Process Example 1"/>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
/* jQuery Dynamic List v 2.0.1 / Copyright 2012 Ike Lin / http://www.apache.org/licenses/LICENSE-2.0.txt */
(function(a){a.fn.dynamiclist=function(d){if(this.length>1){this.each(function(){a(this).dynamiclist(d)});return this}var g=a.extend({itemClass:"list-item",addClass:"list-add",removeClass:"list-remove",minSize:1,maxSize:10,withEvents:false,addCallbackFn:null,removeCallbackFn:null},d);var f=function(o,n,j){var m=o.find("."+j.itemClass).length;if(m<j.maxSize){var l=o.find("."+j.itemClass+":first").clone(j.withEvents);l.find("."+j.removeClass).show().click(function(p){e(o,a(this),p,j)});b(l,m);i(l);var k=o.find("."+j.itemClass+":last");k.after(l);if(j.addCallbackFn!=null){j.addCallbackFn(l)}}if(n!=null){n.preventDefault()}};var e=function(o,k,n,j){var m=o.find("."+j.itemClass).length;var l=k.parents("."+j.itemClass+":first");if(m==j.minSize){i(l)}else{l.remove()}c(o,j);if(j.removeCallbackFn!=null){j.removeCallbackFn(l)}n.preventDefault()};var b=function(j,k){j.find("label, input, select, textarea").each(function(){var m=["class","name","id","for"];for(var n=0;n<m.length;n++){var l=a(this).attr(m[n]);if(l){l=l.replace(/\d+\./,k+".");l=l.replace(/\[\d+\]\./,"["+k+"].")}a(this).attr(m[n],l)}})};var c=function(k,j){k.find("."+j.itemClass).each(function(){var l=k.find("."+j.itemClass).index(this);b(a(this),l)})};var i=function(j){j.find("input[type=text], textarea").val("");j.find("input[type=radio]").attr({checked:false});j.find("input[type=checkbox]").attr({checked:false})};var h=function(k){k.find("."+g.itemClass+":first ."+g.removeClass).hide();var j=k.find("."+g.itemClass).length;while(g.minSize>j){f(k,null,g);j++}k.find("."+g.addClass).click(function(l){f(k,l,g)});k.find("."+g.removeClass).click(function(l){e(k,a(this),l,g)});return k};return h(this)}})(jQuery);
</script>
<script>
(function($) {
$(document).ready(function() {
$("#example1").dynamiclist();
// display form submit data
$("form").submit(function(event) {
event.preventDefault();
var data = "";
$(this).find("input, select").each(function() {
var element = $(this);
if (element.attr("type") != "submit") {
data += element.attr("name");
data += "="
data += element.val();
data += "; "
}
});
alert(data);
//location.reload(true);
});
});
})(jQuery);
</script>
I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)
I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>
I want to create some popup that will tell user when he doesn't enter name, lastname, number or email.
HTML :
<div class="form-group">
<label class="label-block" for="cname" data-new-placeholder="What is your name?">Ime</label>
<input name="firstName" minlength="3" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block" for="cemail">Email</label>
<input name="ctct" type="email" required="required" required class="texbox">
</div>
</div>
<div class=" col-md-6">
<div class="form-group">
<label class="label-block">Prezime</label>
<input name="lastName" type="text" required class="texbox">
</div>
<div class="form-group">
<label class="label-block">Telefon</label>
<input name="number" type="digits" required class="texbox">
</div>
</div>
JS :
<script src="scripts/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function () {
$("#configuration-form").validate({
messages: {
name: {
required: "Error!"
}
}
});
});
</script>
<script>
$("#commentForm").validate();
</script>
That is my code in html and css... I managed to make my textbox turns red when the email is not ok. how to create that popup text.
It looks like you are using Twitter Bootstrap, and they have a popover feature or alert message that you can use: Bootstrap - popovers
HTML :-
Validation for Email.
<input type="text" id="email">
<input type="submit" onclick="validateEmail()" >
JavaScript Code :-
function validateEmail() {
var emailText = document.getElementById('email').value;
var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/;
if (pattern.test(emailText)) {
return true;
} else {
alert('Bad email address: ' + emailText);
document.getElementById("email").style.backgroundColor = "Red";
return false;
}
}
Working Demo for Email Validation.
I hope it will help you.