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.
Related
I'm unable to get a basic if statement inside a jquery $.each loop working. I have a json object that I loop through, and if the value entered in a text box is found in the json object, I return a flag I set as false. But for some reason, the if statement is not executing. Here is the code:
var authorlist = [
{"AUTHOR":"DONNA EDWARDS","COUNTRY":"USA","REGION":"MIDWEST"},
{"AUTHOR":"EMERALD JONES","COUNTRY":"UK","REGION":"EU"},
{"AUTHOR":"SHAKESPEARE","COUNTRY":"UK","REGION":"EU"}];
function checkName() {
var nameIsValid = true;
var nametocheck = $("#name").val();
$.each(authorlist, function(index, val){
//console.log(val.AUTHOR);
if(nametocheck == val.AUTHOR) {
//console.log(val.AUTHOR);
nameIsValid = false;
return false;
}
});
return nameIsValid;
}
$("#btnCheck").on("click", function(){
console.log("The name entered is valid: " + checkName());
});
<form class="form-horizontal" name="paymentInformation" id="paymentInformation" action="verifyOrder.cfm" method="post" role="form">
<div class="form-group">
<fieldset class="col-sm-12">
<!-- Row 1 -->
<div class="row">
<div class="col-sm-6">
<label for="id2" class="col-6 col-form-label">
Book Name
</label>
<input type="form-control" placeholder="Book Name" type="text" id="id2" name="id2" class="col-10">
<button type="button" class="btn btn-primary" id="btnCheck">Check</button>
</div>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
https://jsfiddle.net/wqnkz4v7/
Edit following
var nametocheck = $("#id2").val();
or Use following
$("input[name='name']").val();
You need to address the right id.
var nametocheck = $("#id2").val();
// ^^^^
The error you have is in var nametocheck = $("#name").val();.
The selector according to the html should be "#id2".
<legend>Information</legend>
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<label><strong>{{$val}}</strong></label>
</div>
<script>
var str = "Hello world!";
var res = str.substring(0, 2);
if (res == ee) {
alert("Hello! I am an alert box!");
} else if (res == he) {
document.getElementById("checkbox").checked = true;
}
</script>
<div class="col-xs-12 col-sm-3 col-md-3">
<input type="checkbox" name="operator" id="checkbox" >
</div>
<div class="col-xs-12 col-sm-3 col-md-3">
<input type="checkbox" name="operator" id="checkbox">
</div>
<div class="col-xs-12 col-sm-3 col-md-3">
<input type="checkbox" name="operator" id="checkbox">
</div>
</div>
<br/>
i have included my html piece of code above. i don't know why check box is not responding for this piece of JavaScript.
note: i should use JavaScript in the position between div's
value ee and he should be wrapped in quotes. also note that IDs should be unique, you can rather use common class and use getElementsByClassName to target all of them using class :
var res = str.substring(0, 2);
if(res=='ee'){
alert("Hello! I am an alert box!");
}
else if(res=='he'){
document.getElementsByClassName("checkbox").checked = true;
}
Condition is wrong. If you want check the string element you have to use "" or ''. Otherwise it will treat as a variable.
if(res=="ee"){
alert("Hello! I am an alert box!");
}
else if(res=="he"){
document.getElementById("checkbox").checked = true;
}
This is my simple code which I have been working to just show valid or invalid if the wrong text is inserted but the problem I’m having is that when I hit enter the valid and invalid flashes without staying on screen.
Here is my Fiddle
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
}
}
<form>
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my" onchange="validate()"></input>
<label id="Result"></label>
</form>
What is the mistake i am doing and How can i fix this ?
The problem is that you have your code inside tag. You need to prevent form submission if you want to stay on the page.
I have not included CSS here!!
<div class="container">
<div id="nav">
<div id="search">
<form id="form1">
<button type="button" onclick ="yes" class="fa fa-search"></button>
<input type="text" id="my"></input>
<label id="Result"></label>
</form>
</div>
</div>
</div>
$(document).ready(function(){
$("#form1").submit(function(event){
if ( !validate()) {
alert("Error");
event.preventDefault();
return false;
}
});
});
function validate ()
{
var me = document.getElementById("my").value;
if (me == 'my')
{
document.getElementById("Result").innerHTML = "valid";
document.getElementById("Result").style.color = "green";
return true;
}
else
{
document.getElementById("Result").innerHTML = "invalid";
document.getElementById("Result").style.color = "red";
return false;
}
}
Here is a fiddle. Hope it will help.
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;
}
});
I've added some validation to my jQuery code to check for blank text fields before it posts a message but it doesn't seem to be working. No messages are being posted at all to my wall. Any idea how I can fix this?
HTML
<div id="header">
<div class="container"> <span id="text_header">Virtual Idea Wall</span> </div>
</div>
<div id="main">
<div class="container">
<div id="chat"></div>
</div>
</div>
<div id="footer">
<div class="container">
<p>
<label for="title">Please give your idea a title</label>
<br />
<input type="text" id="title" name="title"/>
</p>
<p>
<label for="message">Please provide details of your idea</label>
<br>
<input type="text" id="message" name="message"/>
</p>
<p>
<input type="submit" id="sendmessage">
</p>
</input>
</div>
</div>
jQuery
jQuery(function ($) {
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function () {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message', '<b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val());
$messageTitle.val('');
$messageBox.val('');
}
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
});
Your click function is not passing in the event "e" so that would stop this from working when you make a call to "e.preventDefault()".
I made this jsfiddle - no socket support - but it does alert my message.
http://jsfiddle.net/4v2QT/
This is the only change (the e passing into the function)
$messageForm.click(function (e) {
... code goes here!
}