So I have a multipart form I am working on where I would like to check the values of each step and run some basic validation on the input fields in that step. I can't seem to figure out how to prevent the form from moving to the next step if fails the validation. Does anyone have an idea how to do this?
<body>
<form name="form1" action="test.php" method="POST">
<div id="page1" data-role="page">
<div data-role="header" data-theme="b" data-position="fixed">
<h1>Page1</h1>
</div>
<div data-role="content">
<fieldset data-role="controlgroup" id="group1">
<input type="text" name="name" id="name" />
<label for="name">Name</label>
<input type="text" name="age" id="age" />
<label for="age">age</label>
</fieldset>
Next
</div>
</div>
<div id="page2" data-role="page">
<div data-role="header" data-theme="b" data-position="fixed">
<h1>Page2</h1>
Back
</div>
<div data-role="content">
<fieldset data-role="controlgroup" id="group2">
<input type="text" name="address" id="address" />
To prevent the submition of the form on the button click if its not valid you need to return false to the click event. Here is my JSFiddle
$("#btnPage2").click(function() {
var isValid = true;//added local variable to track validation
$("#group1 input[type=text]").each(function() {
if((this.value) == "") {
isValid = false;//form was not valid
return false;
}
});
if (! isValid) {//when form is not valid, return false
return false;
}
});
As requested, this is how I would do it when i want to bind the event to all btnPage buttons. It retrieves the group number that the button is on (in this case the number at the end of your btnPage minus 1 is the group number) and uses it in the each statement for validation. Fiddle Here
$('a[id^="btnPage"]').click(function() {
var groupNum = +($(this).attr('id').replace('btnPage', '')) - 1;//get the group number to validate
var isValid = true;//added local variable to track validation
$('#group' + groupNum + ' input[type=text]').each(function() {
if(this.value == "") {
isValid = false;//form was not valid
return false;
}
});
if (! isValid) {//when form is not valid, return false
return false;
}
});
Related
I am trying to develop a form. Before submitting to server i validate it using jquery, everything is working fine except function on submit event, form is being submitted with errors, while checking in console window, error is like this, "unreachable code after return statement",please give some suggestions
Excerpt of html:
<form name="empform" action="editformProcess.php" method="POST" id="empform1"><a name="profileform1"></a>
<div class="row">
<div class="col-md-5 box"><label>First Name </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="firstName" id="fName" required /></div>
</div>
<div class="row ErrorMessg">
<div class="col-md-5 "></div>
<div class="col-md-7 " id="firstNameErrorMsg"> </div>
</div>
<div class="row">
<div class="col-md-5 box"><label>Last Name </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="lastName" /></div>
</div>
<div class="row">
<h3>Contact Details </h3>
<div class="col-md-5 box"><label>Email Id </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="email" name="emailId" required /></div>
</div>
<div class="row">
<div class="col-md-5 box"><label>Mobile Number </label></div>
<div class="col-md-7 boxinput"><span class="colenSpan">: </span><input type="text" name="mobileNumber" id= "mobNum" required /></div>
<div id="mobbox"></div>
</div>
<div class="row ErrorMessg">
<div class="col-md-5"><label></label></div>
<div class="col-md-7" id="mobileNumMess"> </div>
<div id="mobbox"></div>
</div>
<input type="submit" name="submitDetails" value="Submit Details" id="submit"/>
</form>
excerpt of jquery:
$(function(){
//firstNameErrorMsg
$("#firstNameErrorMsg").hide();
$("#mobileNumMess").hide();
var errorFirstName= false;
var mobileNum= false;
$("#fName").focusout(function(){
checkFirstName();
});
$("#mobNum").focusout(function(){
checkMobNum();
});
function checkFirstName(){
var fNameLength = $("#fName").val().length;
if(fNameLength < 5 || fNameLength > 20){
$("#firstNameErrorMsg").html("sholud be between 5-20 charecters ");
$("#firstNameErrorMsg").show();
errorFirstName= true;
}else
{
$("#firstNameErrorMsg").hide();
}
}
function checkMobNum(){
var pattern = new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/);
if(pattern.test($("#mobNum").val())){
$("#mobileNumMess").hide();
}else{
$("#mobileNumMess").html("Invalid Mobile Number");
$("#mobileNumMess").show();
mobileNum = true;
console.log("h from begin sub");
}
}
$("#empform1").on('submit',function(){
//return true;
//console.log("h from begin2 sub1");
var errorFirstName= false;
var mobileNum= false;
checkFirstName();
checkMobNum();
//console.log("under var");
if(errorFirstName == false){
return true;
console.log("under if");
}else{
return false;
}
})
});
You need to correct your code in 2 places.
To solve form submit issue, you need to remove the variable declaration inside submit method
$("#empform1").on('submit',function(){
//return true;
//console.log("h from begin2 sub1");
//var errorFirstName= false;
//var mobileNum= false;
Dont forget to reset the var errorFirstName inside checkFirstName method
} else {
$("#firstNameErrorMsg").hide();
errorFirstName = false;
}]
When an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. Here,
if(errorFirstName == false){
return true;
console.log("under if");
}
is the error. The string is being logged after the return statement. Change this to:
if(errorFirstName == false){
console.log("under if");
return true;
}
I hope this was should fix it, though I am not able to reproduce the error.
Referring to any problems with submit, here's how I would suggest you edit the code:
function checkFirstName(){
var fNameLength = $("#fName").val().length;
if(fNameLength < 5 || fNameLength > 20){
$("#firstNameErrorMsg").html("sholud be between 5-20 charecters ");
$("#firstNameErrorMsg").show();
return true;
}else
{
$("#firstNameErrorMsg").hide();
return false
}
}
function checkMobNum(){
var pattern = new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/);
if(pattern.test($("#mobNum").val())){
$("#mobileNumMess").hide();
return false;
}else{
$("#mobileNumMess").html("Invalid Mobile Number");
$("#mobileNumMess").show();
console.log("h from begin sub");
return true;
}
}
$("#empform1").on('submit',function(){
var errorFirstName= checkFirstName();
var mobileNum= checkMobNum();
if(errorFirstName == false){
return true;
console.log("under if");
}else{
return false;
}
})
What you apparently intended to do with the code was to modify the errorFirstName and mobileNum in the scope of the function (the event handler) according to the check functions. But it doesn't work that way.
When you changed the variables in the check functions, the global variable was referred first of all. That's not something I guess you had intended.
As a good practice, I suggest you return the test results, as I have in the edited code.
This problem could also be solved by removing the lines of code which declares local variables with the same name in the handler function.
I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem
I am unable to figure out why my page will not redirect to the set page. Whenever the condition is met, the page simply refreshes. I have gone into the browser console and pasted my redirect code, and it does redirect.
Full JavaScript Function:
function formSubmit(){
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value.length == 0 || formFN.value == null){
window.alert("Please enter your first name.");
return false;
}
else if( formLN.value.length == 0 || formLN.value == null){
window.alert("Please enter your last name.");
return false;
}
else
{
document.location = "resultPage.html";
return false;
}
}
HTML Part:
<div id="form">
<form action="">
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button onclick="formSubmit();">
Submit
</button>
<!-- <input type="submit" value="Submit" onclick="formSubmit();"> -->
</form>
</div>
By default, button elements have a type attribute of submit. Based on your question, you probably want this instead:
<button type="button" onclick="formSubmit();">
Submit
</button>
If you want a more general solution, you'd be better off capturing and handling the submit event on the form since things like pressing return in an input would trigger a submit as well.
window.addEventListener("load", function() {
document.getElementById("form").getElementsByTagName("form")[0].addEventListener("submit",function(event) {
event.preventDefault(); // Stop the normal action for this event
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value == null || formFN.value.length == 0 ){
alert("Please enter your first name.");
}
else if( formLN.value == null || formLN.value.length == 0 ){
alert("Please enter your last name.");
}
else {
document.location = "resultPage.html";
}
});
});
<div id="form">
<form>
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button>Submit</button>
</form>
</div>
Edit: It occurs to me that you should check for nulls before checking for length. (If .value is null then checking .value.length will throw an error.) Adjusted code accordingly.
In below code actually I got form design in popup using onload(). In function login() first I check every field is required then in else part I call loginvalidate.php page without page refresh in this page I perform validation in php and if any error show it in
<div id="result" style="color:red;"></div>
Division, But my query is that after if part is completed in login function and when I click on button in else part our page is reloaded because of this reload I can't access my loginvalidate.php page why this is happen please suggest me,
<!doctype html>
<html>
<head>
<script src="jquery-1.11.3.js"></script>
<meta charset="utf-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script>
function login(){
var email=document.getElementById("email").value;
var password=document.getElementById("pass").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(email=="" || password==""){
alert("Every Field Is Requird");
email.password.focus();
return false;
}else{
//alert("hii");
$.post('custom-look/loginvalidate.php',{uemail:email,upass:password}, //email,pass ->textbox name
function(data){
$('#result').html(data);
});
return false;
}
}
function popup(){
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
</script>
</head>
<body onload="popup();">
<div id="light" class="white_content" style="height:53%">
<img class="close" src="/shopeeon/custom-look/newloginpopup/close.jpg" class="close" href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none';history.go(-1);"></img>
<!--go back to previous page using "history.go(-1)" onclick-->
<div id="abc">
<div id="popupContact-login" class="col-sm-12" >
<form action="" id="login-form" method="post" name="form">
<div style="color:orange;text-align:center;width:100%;">
<h2 style="margin:0px;">Login to Earn Extra Cashback</h2>
<div id="result" style="color:red;"></div>
</div><br/>
<div class="col-sm-6 align="center" style="border-right:1px solid gray;" > <?php $reg1 = <<<var<b style="font-size:20px;font-family:arial;"> Registered User,</b> var; $reg2=<<<var<b style="color:blue;font-size:20 px;font-family:arial;"> Sign In Here </b> var; echo $reg1.$reg2; ?> </br> <input type="email" id="email" class="form-control" name="uemail" placeholder="Enter email" required/><br/>
<input type="password" id="pass" class="form-control" name="upass" placeholder="Enter password" required/><br/>
<button type="submit" onclick="return login()" id="submit" name="submit" value="submit" class="btn btn-info active btn-md">SIGN IN</button><br/>
Else Redirect without Sign In
</div>
<div class="col-sm-6" > <?php $str1 = <<<var <b style="font-size:20px;font-family:arial;"> New User,</b> var; $str2=<<<var <b style="color:blue;font-size:20 px;font-family:arial;"> Sign Up Here </b> var; echo $str1.$str2;?>
<img src="/shopeeon/custom-look/newloginpopup/link.png" height="38"></img><br/> <?php $s1 = <<<var <b style="font-size:12px;font-family:arial;"><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> WE OFFER CASHBACK WHEN YOU SHOP VIA US.</br><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> OVER 2 LAKH CASHBACK PAID.</br><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> OVER 1 LAKH HAPPY CUSTOMERS.</br><img src="/shopeeon/custom-look/newloginpopup/star.png" height="15" width="15"></img> 25+ PARTNERS SITES.</br>var; echo $s1;?>
</div >
</form>
</div>
</div>
</div>
<div id="fade" class="black_overlay"></div>
</body>
</html>
While click the button form submit will trigger, it's reload the page. So give onsubmit="return false" to form for prevent the page load.
Like below code
<form onsubmit="return false">
</form>
Hope this will help you.
1st: what that line expect to do?? email.password.focus(); it will give you an error .. so you can use
if(email=="" || password=="")
{
alert("Every Field Is Requird");
if(email == ""){
email.focus();
}
// check the same way for password
}
else......
2nd: better to don't mix jquery with pure javascript
3rd in your function it submit a form before prevent the page from reloading so you can use
in html
<form onsubmit="login();"> // instead of the submit input click event
and your function
function login()
{
var email=$('#email').val();
var password=$("#pass").val();
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(email=="" || password=="")
{
alert("Every Field Is Requird");
//email.password.focus();
}
else
{
//alert("hii");
$.post('custom-look/loginvalidate.php',{uemail:email,upass:password}, //email,pass ->textbox name
function(data)
{
$('#result').html(data);
});
}
return false;
}
or you can use e.preventDefault();
<form onsubmit="login(e);"> // instead of the submit input click event
and your function
function login(e)
{
e.preventDefault();
var email=$('#email').val();
var password=$("#pass").val();
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(email=="" || password=="")
{
alert("Every Field Is Requird");
//email.password.focus();
}
else
{
//alert("hii");
$.post('custom-look/loginvalidate.php',{uemail:email,upass:password}, //email,pass ->textbox name
function(data)
{
$('#result').html(data);
});
}
//return false;
}
I'm trying to hide part of the form with the button disabled and have the user click on the button to show rest of form when previous fields are filled in. Can anyone help? Here's my code as an example:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1"/><br/>
<label>Field 2:</label>
<input type="text" class="field2"/><br/>
<label>Field 3:</label>
<input type="text" class="field3"/><br/>
</div>
<div align="center">
<button id="show_form" onClick = "this.style.display= 'none'" disabled="disabled">
Enter Billing Info</button>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
JQUERY
<script>
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
$("#show_form").prop("disabled", true);
$("#group2").hide();
$("#show_form").show();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
</script>
Try this jQuery:
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
/* This will hide the bottom form and disable the button again if
* any of the field above will be emptied.
* NOTE: This will just hide the form; it will not clear the fields.
*/
$("#show_form").prop("disabled", true);
$("#group2").hide();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
This will enable the button when all the fields in the initial form are filled. Then the user will be able to click on the button to see the rest of the form.
You just need to loop through each input and check if a value is set when the button is clicked like this:
$('#show_form').click(function () {
var fields = $('.js-field');
var pass = true;
for (var i = 0; i < fields.length; i++) {
if (!$(fields[i]).val()) {
pass = false;
}
}
if (pass === true) {
$('#group2').show();
}
});
I also needed to add some classes to your html:
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1 js-field"/><br/>
<label>Field 2:</label>
<input type="text" class="field2 js-field"/><br/>
<label>Field 3:</label>
<input type="text" class="field3 js-field"/><br/>
</div>
<button type="button" id="show_form" value="Show_Form">Enter Billing
Info</button>
<div id="group2" style="display: none;">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
To see it in action visit this fiddle.
You can add some logic to the click event and check all the input fields to have a value like this
$("#show_form").click(function(){
var allFilled = true;
$('#group1').find('input').each(function(){
//if someone is empty allFilled will keep false
if(this.value === ''){
allFilled = false;
//this breaks the each
return false;
}
});
if(allFilled){
$("#group2").show();
}
});
Keep in mind the previous code only work with input fields.