next button with enter key in parsley validator - javascript

I used parsley validation pack for two step form.
this is html:
<form action="#" method="POST" autocomplete="off" class="enter-form" data-parsley-validate="" data-parsley-focus="first">
<div class="form-group form-section">
<label for="email"><b>email or phone number:</b></label>
<input type="text" title="enter email or phone number" autofocus="autofocus" tabindex="1" class="form-control" id="email" required="" data-parsley-emailorid="" />
</div>
<div class="form-group form-section">
<label for="pwd"><b>password:</b></label>
<input type="password" title="enter password" tabindex="2" class="form-control" id="pwd" required="" />
</div>
<div class="form-navigation">
<button type="button" class="previous btn btn-primary pull-left">
previous >
</button>
<button type="button" class="next btn btn-primary pull-right" id="nextBtn">
< next
</button>
<button type="submit" class="btn btn-rang pull-right">
enter
</button>
<span class="clearfix"></span>
</div>
</form>
and this is java script for multi step verification:
$(document).ready(function () {
var $sections = $('.form-section');
function navigateTo(index) {
$sections
.removeClass('current')
.eq(index)
.addClass('current');
$('.form-navigation .previous').toggle(index > 0);
var atTheEnd = index >= $sections.length - 1;
$('.form-navigation .next').toggle(!atTheEnd);
$('.form-navigation [type=submit]').toggle(atTheEnd);
}
function curIndex() {
return $sections.index($sections.filter('.current'));
}
$('.form-navigation .previous').click(function() {
navigateTo(curIndex() - 1);
});
$('.form-navigation .next').click(function() {
$('.enter-form').parsley().whenValidate({
group: 'block-' + curIndex()
}).done(function() {
navigateTo(curIndex() + 1);
});
});
$sections.each(function(index, section) {
$(section).find(':input').attr('data-parsley-group', 'block-' + index);
});
navigateTo(0);
});
$(document).ready(function () {
var dummyEmail = $('<input data-parsley-type="email">').parsley();
var dummyDigits = $('<input data-parsley-pattern="\[0-9]{11}">').parsley();
window.Parsley.addValidator('emailorid', {
validateString: function(data) {
return dummyDigits.isValid(true, data) || dummyEmail.isValid(true, data);
},
messages: {
en: "Is neither a nine digit long number nor a valid email address"
}
});
});
In step one I couldn't use "enter" key for going to next step. So I wrote this code to trigger "#nextBtn" on "enter" key:
$(document).ready(function () {
var input = document.getElementById("email");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("nextBtn").click();
}
});
});
But I have a problem now. when I go to next step using "enter" key, it doesn't focus on password input.
My question is: How can I focus on password input when going to next step using "enter" key?

You can get password input with:
document.getElementById("pwd").focus();
Or with jQuery:
$('#pwd).focus();
So, when your JavaScript code detects on press enter, just get the html element to focus, and use .focus() function.
Jquery DOCS: https://api.jquery.com/focus/
JS Doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

Related

Form is not submitting , not sure if this has to do with the captcha

I am trying to tie the code in together.
I recently just made a form and found a captcha on codepen that I wanted to try out
But for some reason I cant get the captcha to validate the form even though it does perform the calculation. Any idea what could be causing the problem in my code? Thanks in advance.
<form
class="form mt-4"
method="POST"
action="action_page.php">
<!-- Name Field -->
<div class="form-group">
<label for="name">Name:</label>
<input
type="text"
name="name"
id="name"
placeholder="Enter Your Name"
class="form-control"
required
/>
</div>
<!-- Email Field -->
<div class="form-group">
<label for="email"
>Email Address:</label
>
<input
type="email"
name="email"
id="email"
placeholder="Enter Your Email"
class="form-control"
required
/>
</div>
<!-- Password Field -->
<div class="form-group">
<label for="password"
>Password:</label
>
<input
type="password"
name="password"
minlength="8"
id="password"
placeholder="Password"
class="form-control"
required
/>
</div>
<!-- Confirm Password Field -->
<div class="form-group">
<label for="confirm_password"
>Confirm Password:</label
>
<input
type="password"
name="confirm_password"
minlength="8"
id="confirm_password"
placeholder="Confirm Password"
class="form-control"
required
/>
</div>
<!-- Telegram API Token Field -->
<div class="form-group">
<label for="telegram_token"
>Telegram API Token:</label
>
<input
type="text"
name="telegram_token"
id="telegram_token"
placeholder="Enter Telegram API Token"
class="form-control"
required
/>
</div>
<!-- Telegram Chat ID Field -->
<div class="form-group">
<label for="telegram_id"
>Telegram Chat ID:</label
>
<input
type="text"
name="telegram_id"
id="telegram_id"
placeholder="Enter Telegram Chat ID"
class="form-control"
required
/>
</div>
<!-- Captcha Field -->
<div class="form-group">
<label>Are you human?</label>
<br />
<label class="submit__control">
<div
class="submit__generated"
></div>
<i
class="fa fa-refresh"
></i>
<span
class="submit__error hide"
>Incorrect value</span
>
<span
class="submit__error--empty hide"
>Required field cannot
be left blank</span
>
</label>
</div>
<!-- Register Button -->
<div class="form-group">
<button
type="submit"
class="btn btn-info btn-block"
>
Register
</button>
var a,
b,
c,
submitContent,
captcha,
locked,
validSubmit = false,
timeoutHandle;
// Generating a simple sum (a + b) to make with a result (c)
function generateCaptcha() {
a = Math.ceil(Math.random() * 10);
b = Math.ceil(Math.random() * 10);
c = a + b;
submitContent =
"<span>" +
a +
"</span> + <span>" +
b +
"</span>" +
' = <input class="submit__input" type="text" maxlength="2" size="2" required />';
$(".submit__generated").html(submitContent);
init();
}
// Check the value 'c' and the input value.
function checkCaptcha() {
if (captcha === c) {
// Pop the green valid icon
$(".submit__generated").removeClass("unvalid").addClass("valid");
$(".submit").removeClass("overlay");
$(".submit__overlay").fadeOut("fast");
$(".submit__error").addClass("hide");
$(".submit__error--empty").addClass("hide");
validSubmit = true;
} else {
if (captcha === "") {
$(".submit__error").addClass("hide");
$(".submit__error--empty").removeClass("hide");
} else {
$(".submit__error").removeClass("hide");
$(".submit__error--empty").addClass("hide");
}
// Pop the red unvalid icon
$(".submit__generated").removeClass("valid").addClass("unvalid");
$(".submit").addClass("overlay");
$(".submit__overlay").fadeIn("fast");
validSubmit = false;
}
return validSubmit;
}
function unlock() {
locked = false;
}
// Refresh button click - Reset the captcha
$(".submit__control i.fa-refresh").on("click", function () {
if (!locked) {
locked = true;
setTimeout(unlock, 500);
generateCaptcha();
setTimeout(checkCaptcha, 0);
}
});
// init the action handlers - mostly useful when 'c' is refreshed
function init() {
$("form").on("submit", function (e) {
e.preventDefault();
if ($(".submit__generated").hasClass("valid")) {
// var formValues = [];
captcha = $(".submit__input").val();
if (captcha !== "") {
captcha = Number(captcha);
}
checkCaptcha();
if (validSubmit === true) {
validSubmit = false;
// Temporary direct 'success' simulation
submitted();
}
} else {
return false;
}
});
// Captcha input result handler
$(".submit__input").on(
"propertychange change keyup input paste",
function () {
// Prevent the execution on the first number of the string if it's a 'multiple number string'
// (i.e: execution on the '1' of '12')
window.clearTimeout(timeoutHandle);
timeoutHandle = window.setTimeout(function () {
captcha = $(".submit__input").val();
if (captcha !== "") {
captcha = Number(captcha);
}
checkCaptcha();
}, 150);
}
);
// Add the ':active' state CSS when 'enter' is pressed
$("body")
.on("keydown", function (e) {
if (e.which === 13) {
if ($(".submit-form").hasClass("overlay")) {
checkCaptcha();
} else {
$(".submit-form").addClass("enter-press");
}
}
})
.on("keyup", function (e) {
if (e.which === 13) {
$(".submit-form").removeClass("enter-press");
}
});
// Refresh button click - Reset the captcha
$(".submit-control i.fa-refresh").on("click", function () {
if (!locked) {
locked = true;
setTimeout(unlock, 500);
generateCaptcha();
setTimeout(checkCaptcha, 0);
}
});
// Submit white overlay click
$(".submit-form-overlay").on("click", function () {
checkCaptcha();
});
}
generateCaptcha();
// Password Match Function
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
It was the function for submit was missing

How to disable special characters on the press of Enter button without preventDefault()?

I have a search field:
<div class="search-fill">
<input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." value="#ViewBag.Terms"/>
</div>
and a button related to it:
<div class="search-submit">
<button id="searchbutton" class="search-button"><i class="fa fa-search" onclick="removeSpecialChar()"></i></button>
This code does not help when the user presses the Enter key. I know we can disable the Enter through preventDefault(), but is there any other way to do this, as I want the user to be able to search even on clicking Enter?
Check this
$(function () {
$('[type="search"]').bind('paste input', removeSpecialChars);
})
function removeSpecialChars(e) {
var self = $(this);
setTimeout(function () {
var initVal = self.val(),
outputVal = initVal.replace(/[^A-Z0-9]+/i, '');
if (initVal != outputVal) self.val(outputVal);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" name="search" id="search" class="autocomplete" autocomplete="off" placeholder="Search..." />
document.querySelector("#search").addEventListener("input", ({ target }) => {
const regEx = /([.*+?^$|(){}\[\]])/mg; // example, compose regexp you need
target.value = target.value.replace(regEx, "");
})

Show/Hide Password in Two Inputs

I' trying to build a form in which the users can change the values of two password inputs, one for a password and a second one to verify the password.
So in order to make the user aware of what he types and to make sure both of his/her password match with one another and tried to implemente a method in which he can just check a checkbox to show his password.
The current javascript method works with just one input but I would like to have it working with both input and not just one. I would like as well to show the password of both input without having to check their own corresponding checkbox(for example if a check one checkbox it should display text in both inputs).
This is the current javascript method that I have:
// First Code //
function addEvent (el, event, callback) {
if ('addEventListener' in el) {
el.addEventListener(event, callback, false);
} else {
el['e' + event + callback] = callback;
el[event + callback] = function () {
el['e' + event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}
function removeEvent(el, event, callback) {
if ('removeEventListener' in el) {
el.removeEventListener(event, callback, false);
} else {
el.detachEvent('on' + event, el[event + callback]);
el[event + callback] = null;
el['e' + event + callback] = null;
}
}
// Second Code //
(function() {
var pwd = document.getElementById('password');
var chk = document.getElementById('showpass');
addEvent(chk, 'change', function(e) {
var target = e.target || e.srcElement;
try {
if (target.checked) {
password.type = 'text';
} else {
password.type = 'password';
}
} catch(error) {
alert('This browser cannot switch type');
}
});
}());
<!-- First Password -->
<div class="form-group">
<label for="password">Password</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-lock" aria-hidden="true"></i>
</div>
<input type="password" name="password" value="" id="password" class="form-control">
<div class="input-group-addon"><input type="checkbox" id="showpass"></div>
</div>
</div>
<!-- Second Password -->
<div class="form-group">
<label for="password2">Confirm Password</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-lock" aria-hidden="true"></i>
</div>
<input type="password" name="password2" value="" id="password2" class="form-control">
<div class="input-group-addon"><input type="checkbox" id="showpass"></div>
</div>
</div>
Thanks in advance.
Change the type of both inputs at once:
var pwd = document.getElementById('password');
var confirm = document.getElementById('password2');
...
if (target.checked) {
pwd.type = 'text';
confirm.type = 'text';
} else {
pwd.type = 'password';
confirm.type = 'password';
}
Added a little fiddle to toggle the password type.
https://jsfiddle.net/xpvt214o/321232/
JS
var $vp = $('.vp');
$vp.on('click', function() {
var $target = $(this).siblings('input[name*="password"]');
if ($target.attr('type') == "password") {$target.attr('type','text');}
else {$target.attr('type','password');}
});
HTML
<div style="width:100%;float:left;margin:0 0 16px 0;">
<p>Password 1</p>
<input type="password" name="password" val="" />
<span class="vp">View password</span>
</div>
<div style="width:100%;float:left;margin:0 0 16px 0;">
<p>Password 2</p>
<input type="password" name="password2" val="" />
<span class="vp">View password</span>
</div>
The function looks for the click event of the span "vp" and get's its sibling input element, checks the type attribute and toggles it to and from text/password. The name of the inputs must contain "password" (in lowercase).

form validation problems with jquery / javascript

This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>

how to use single button click to change placeholder and capture new data on same button click event

<div id="abc" class="first">
<input type="text" placeholder="Number" id="no" class="contact">
<input type="text" placeholder="Pass" id="pass" class="password">
<div class="btn1" role="group">
<button type="button" onclick="change()" class="btnregi">Register
</button>
</div>
----------
javascript function
var entry=0;
function change()
{
if(entry==0)
{
document.getElementById("no").placeholder = "Enter user name...";
document.getElementById("pass").placeholder = "Enter user password";
entry++;
}
else
{
var newuser=document.getelementById("no").value;
var newpass=document.getelementById("pass").value;
alert("you entered new username"+newuser);
alert("you entered new password"+newpass);
}
i want to change placeholder values onclick event and again with same button click and method i want fetch input data. i attached my code but it wont working.
You had misspelled the getElementById in these two lines. Apart from that the code seems to be working fine to me.
var newuser = document.getElementById("no").value;
var newpass = document.getElementById("pass").value;
var entry = 0;
function change() {
if (entry == 0) {
document.getElementById("no").placeholder = "Enter user name...";
document.getElementById("pass").placeholder = "Enter user password";
entry++;
} else {
var newuser = document.getElementById("no").value;
var newpass = document.getElementById("pass").value;
alert("you entered new username: " + newuser);
alert("you entered new password: " + newpass);
}
}
<div id="abc" class="first">
<input type="text" placeholder="Number" id="no" class="contact">
<input type="text" placeholder="Pass" id="pass" class="password">
<div class="btn1" role="group">
<button type="button" onclick="change()" class="btnregi">Register
</button>
</div>

Categories

Resources