jQuery autoruns functions on change events when page is loaded - javascript

I have made a function that validates inputs with for different kind of strings. I am having serious issues with a few things. I call it on form submit and for each input on change. I have written my code below and then the calling of function. Thing is: when I call it on change and refresh the page, it automatically runs the validations on change when the page is loading and renders the errors.
var Val = {
'string': function(ident, req, regexp, offset, limit) {
var ele = $(document.getElementById(ident));
Val.errors = false;
if (!ele.val() && req == 1) {
alert('blank');
Val.errors = true;
$("#" + ident + "Error").html("This field cannot be empty.");
$("#" + ident + "Error").show("fast");
}else if ((ele.val().length <= offset || ele.val().length > limit) && Val.errors == false) {
alert('not long enough');
Val.errors = true;
$("#" + ident + "Error").html("This field must be between " + offset + " & " + limit + " charecters long");
$("#" + ident + "Error").show("fast");
}else if (regexp !== null) {
switch (regexp) {
case 'text':
var regEx = /^([a-zA-Z]+)$/g;
break;
case 'number':
var regEx = /^([0-9]+)$/g;
break;
case 'email':
var regEx = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/g;
break;
case 'date':
var regEx = /^([123]0|[012][1-9]|31)-(0[1-9]|1[012])-(19[0-9]{2}|2[0-9]{3})$/g;
break;
case 'alphanum':
var regEx = /^([a-zA-Z0-9_\-\.]+)$/g;
break;
default:
break;
}
if (!regEx.test(ele.val()) && Val.errors == false) {
alert('not valid');
Val.errors = true;
$("#" + ident + "Error").html("This field is not valid");
$("#" + ident + "Error").show("fast");
}
}
if (!Val.errors){
$("#" + ident + "Error").hide("fast");
}
},
'send': function() {
if (!Val.errors) {
$('#form').submit();
}
}
}
Calling of the function:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Validations</title>
<script type="text/javascript" language="JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript" src="js/gcui.lsat.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#send').click(function(){
checkEmail();
checkUsername();
Val.send();
});
$('#emailID').change(checkEmail());
$('#username').change(checkUsername());
function checkEmail(){
Val.string('email', 1, 'username', 10, 100);
}
function checkUsername(){
Val.string('username', 1, 'alphanum', 5, 15);
}
});
</script>
</head>
<body>
<form id="form" action="">
<input type="text" id="email" name="email" title="Email" />
<input type="text" id="username" name="username" title="Username" />
<input type="button" id="send" value="Submit" />
</form>
Email: <div id="emailError"></div><br/>
Username: <div id="usernameError"></div>
</body>
</html>

$('#emailID').change(checkEmail());
Means "Run checkEmail and pass the return value to the change method"
You want:
$('#emailID').change(checkEmail);
Meaning "Pass the checkEmail function to the change method"

In your $('#send').click(function(){ you do submit it two times. The first time when you do the validation and the second time when the button press is fired. Add the line Return False; just after the Val.send(); and you only get the forum to submit if there form are filled out correct

Related

Perform validation on input tag before form is submitted

I have form which is POSTING all the values but I need to perform validation on phone number input field.
I have tried to apply click event on input tag using id but then HTML5 validation(required) goes off
<form name="frm" method="post" id="callForm" >
<input type="tel" id="phone" name="phone" placeholder="(XXX) XXX-XXXX" required/>
<input id="submitbtn" value="Call Me!" type="submit" />
</form>
Js:
$('#submitbtn').click(function() {
if((frm.phone.value).length < 10)
{
alert("Phone number should be minimum 10 digits");
frm.phone.focus();
return false;
}
return true;
});
link to code pen: https://codepen.io/rahulv/pen/rrwBdq
JavaScript:
$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();
if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$this.val(output);
}
});
});
Use this
$('#submitbtn').click(function() {
if((frm.phone.value).length > 0)
{
if((frm.phone.value).length < 10)
{
alert("Phone number should be minimum 10 digits");
frm.phone.focus();
return false;
}
$( "#callForm" ).submit();
}
});
Disable html5 validation on your form
<form name="frm" method="post" id="callForm" novalidate>
Add the 'novalidate' attribute.

Border outline keeps reverting to original a second after being changed in js

you're help would be appreciated with this simple but mind boggling question.
I have a contact form on which the user click submit, will run a vigorous error checking function I hard-coded myself. The error checking will aplly a red border around every form element that doesn't pass the validation test followed by an alert pop up telling the user a detailed list of where the error is located and what the error is. This all works fine except for the border on each form element being set to red. It works for a split second, long enough for you to see, before strangely reverting back to the original border colour. What on Earth is going on? It is as if there is something else over-riding this code???
Another issue discovered
I also just discovered that it doesn't alert the user like it is supposed to when all the boolean check variables are true. I even ran this alert(fnameCheck + ", " + lnameCheck + ", " + emailCheck + ", " + topicCheck + ", " + messageCheck + ", " + termsAndConsCheck); and the alert just didn't show. There is something going on here... and I don't think it is that function. I could be wrong but I have used this function elsewhere and it worked (although it had less boolean variables to check)
Here is the code...
<div class="body" style="height:560px"> <!-- This is the body --><br />
<span style="font-size:50px">Contact Us</span><br />
<div style="margin-left:20px; text-align:left">
Please feel free to enter your details below to contact us.<br />
<span style="font-size:14px; color:grey">* = required field</span><br /><br />
<form name="contactForm"> <!-- This is a form -->
First name*:<br />
<input name="fname" type="text"><br />
Last name*:<br />
<input name="lname" type="text"><br />
Email*: <br /><input name="email" type="text"><br /><br />
My comment/ enquiry concerns*:<br />
<select id="topic">
<option value="Select a topic" selected>Select a topic</option>
<option value="Billing Questions">Billing Questions</option>
<option value="Returns/ Exchanges">Returns/ Exchanges</option>
<option value="Website Enquiries">Website Enquiries</option>
<option value="Product Enquiries">Product Enquiries</option>
<option value="Other">Other</option>
</select><br /><br />
Message*:<br /><textarea id="message"></textarea>
<br /><br />
If you'd like to send us a file, you may do so below but ensure that the file is no larger than 50MB.
<br /><input type="file" name="myFile">
<br><br />
You agree to the Privacy Policy (click to confirm)*.
<input name="tandc" type= "checkbox"><br /><br />
<button onclick="submitForm()">Hi</button>
<input type="reset" value="Reset">
</form>
</div>
</div>
Here is ALL of the Javascript (all of it isn't relevant but there may be something else in here causing the issue)
<script>
document.getElementById("cover").style.display = "none";
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var username="";
function checkCookie() {
username = getCookie("username");
if (username != "") {
document.getElementById("topnavbar").innerHTML = "Welcome, " + username + ". | ";
}
}
checkCookie();
/* THIS IS THE RELEVANT STUFF FROM HERE DOWN TO THE NEXT COMMENT */
var topic = "Select a topic";
document.getElementById('topic').addEventListener("change", function() {
switch(this.value){
case "Select a topic":
topic = "Select a topic"
break;
case "Billing Questions":
topic = "Billing Questions"
break;
case "Returns/ Exchanges":
topic = "Returns/ Exchanges"
break;
case "Website Enquiries":
topic = "Website Enquiries"
break;
case "Product Enquiries":
topic = "Product Enquiries"
break;
case "Other":
topic = "Other"
break;
}
});
function submitForm(){
var firstName = contactForm.fname.value;
var lastName = contactForm.lname.value;
var email = contactForm.email.value;
var message = contactForm.message.value;
var fnameCheck = false;
var lnameCheck = false;
var emailCheck = false;
var topicCheck = false;
var messageCheck = false;
var termsAndConsCheck = false;
var errorMsg = "";
if(isNaN(firstName)&&firstName!=""){
fnameCheck = true;
}else{
fnameCheck = false;
if(fnameCheck == ""){
errorMsg += "First Name - The field is empty \n";
}else{
errorMsg += "First Name - Please ensure it contains no numbers or symbols \n";
}
}
if(isNaN(lastName)&&lasttName!=""){
lnameCheck = true;
}else{
lnameCheck = false;
if(lnameCheck == ""){
errorMsg += "Last Name - The field is empty \n";
}else{
errorMsg += "Last Name - Please ensure it contains no numbers or symbols \n";
}
}
if(email.indexOf("#") == -1 || email == ""){
emailCheck == false;
if(email == ""){
errorMsg += "Email - The field is empty \n";
}else{
errorMsg += "Email - This is not a valid email address\n";
}
}else{
emailCheck = true;
}
if(topic == "Select a topic"){
topicCheck = false;
errorMsg += "Topic - Please select a topic \n";
}else{
topicCheck = true;
}
if(message == ""){
messageCheck = false;
errorMsg += "Message - Please enter a message \n";
}else{
messageCheck = true;
}
if(!contactForm.tandc.selected){
termsAndConsCheck = false;
errorMsg += "Terms and Conditions - Please tick the checkbox \n";
}else{
termsAndConsCheck = true;
}
if(fnameCheck && lnameCheck && emailCheck && topicCheck && messageCheck && termsAndConsCheck){
alert("form submitted!");
}else{
if(!fnameCheck){
contactForm.fname.style.borderColor = "red";
}
if(!lnameCheck){
contactForm.lname.style.borderColor = "red";
}
if(!emailCheck){
contactForm.email.style.borderColor = "red";
}
if(!topicCheck){
document.getElementById("topic").style.borderColor = "red";
}
if(!messageCheck){
contactForm.message.style.borderColor = "red";
}
if(!termsAndConsCheck){
contactForm.tandc.style.outline = "1px solid red";
}
alert("Please fix the fields listed below... \n\n" + errorMsg + "\nThank you.");
}
}
/* THIS IS THE END OF THE RELEVANT CODE */
</script>
<script type="text/javascript" src="./jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#slider").animate({
"left": $(".item:first").position().left + "px",
"width": $(".item:first").width() + "px"
}, 0);
$(".item").hover(function() {
$("#slider").stop();
$("#slider").animate({
"left": $(this).position().left + "px",
"width": $(this).width() + "px"
}, 500);
});
$(".item").on("mouseout", function() {
$("#slider").stop();
$("#slider").animate({
"left": $('#four').position().left + "px",
"width": $('#four').width() + "px"
}, 500);
});
});
</script>
All I needed to do was change the line
<button onclick="submitForm()">Hi</button>
to
<button type="button" onclick="submitForm()">Submit</button>
Thank you for everybody's help!!!
It looks to me like it's working, but you're not preventing the form from submitting if there are errors. The highlights are happening, the message box pops up, but then the form submits and you lose it all.
Change your button to:
<button type="button" onclick="submitForm()">Hi</button>

Array value not accesible in another function in javascript

I am developing a simple address book. I am using four different arrays to store name,phone no ,address and email of user.When I am calling add() method its adding values to these arrays,but when I am calling display the details its showing address book empty and all these arrays empty. Thanks in advance please help..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="addressBook.css" />
<script src="jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
add();
});
$('#delete').click(function () {
remove_con();
});
$('#view').click(function () {
display();
});
});
</script>
<script type="text/javascript">
var BOOK = new Array();
var BOOKNO = new Array();
var ADDR = new Array();
var EMAIL = new Array();
function add() {
//Take values from text fields
var conname = document.getElementById('userNam').value;
var lenname = BOOK.length;
var x = BOOK.indexOf(conname);
var conno = document.getElementById('userNo').value;
var lenno = BOOKNO.length;
var y = BOOKNO.indexOf(conno);
var conaddr = document.getElementById('userAdd').value;
var lenaddr = ADDR.length;
var z = ADDR.indexOf(conaddr);
var conemail = document.getElementById('userEmail').value;
var lenemail = EMAIL.length;
var w = EMAIL.indexOf(conemail);
//Validations
if (conname.length == 0) {
alert("Name field cannot be blank");
return;
}
else if (conno.length == 0) {
alert("Phone number field cannot be Left blank");
return;
}
else if (conno.length != 10) {
alert("Enter a Valid Phone Number");
return;
}
else if (conaddr.length == 0) {
alert("Address field cannot be blank");
return;
}
else if (conemail.length == 0) {
alert("Email field cannot be blank");
return;
}
//RegEX
alphaExp = /^[a-zA-Z]+$/;
numExp = /^[0-9]+$/;
betaExp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!conname.match(alphaExp)) {
alert("Please enter alphabets only");
return;
}
else if (!conno.match(numExp)) {
alert("Please enter numerals only");
return;
}
else if (!conemail.match(betaExp)) {
alert("Please enter a valid email");
return;
}
else if (y >= 0) {
alert("Phone number already Present");
return;
}
else {
BOOK[lenname] = conname;
BOOKNO[lenno] = conno;
ADDR[lenaddr] = conaddr;
EMAIL[lenemail] = conemail;
var l = BOOK.length;
alert("Contact " + conname + " Added Sucesfully!!!!" +l);
return BOOK,BOOKNO,ADDR,EMAIL;
}
}
function display() {
//document.getElementById('hiddenDiv').style.display = "block";
BOOK = BOOK.sort();
var l = BOOK.length;
alert(l);
var view = "";
if (l == 0) {
document.getElementById('hiddenDiv').innerHTML = "ADDRESS BOOK EMPTY!!!";
}
if (l >= 1) {
view = view + "<table border=1px><tr><td><B>NAME</B></td><td><B>PHONE NUMBER</B></td><td><B>ADDRESS</B></td><td><B>EMAIL</B></td>";
for (var i = 0; i < BOOK.length; i++) {
view = view + "<tr><td>" + BOOK[i] + "</td><td>" + BOOKNO[i] + "</td><td>" + ADDR[i] + "</td><td>" + EMAIL[i] + "</td></tr>";
}
document.getElementById('hiddenDiv').innerHTML = view + "</table>";
}
}
function remove_con() {
var remname = prompt("Enter the name to be removed");
var remlen = BOOK.LENGTH;
/*var remnam=document.getElementById('name').value;
var remno=document.getElementById('phno').value;*/
var z = BOOK.indexOf(remname);
var z1 = z;
var z2 = z;
var z3 = z;
if (remlen == 0) {
alert("ADDRESS BOOK IS EMPTY");
return;
}
if (z >= 0) {
BOOK.splice(z, 1);
BOOKNO.splice(z1, 1);
ADDR.splice(z2, 1);
EMAIL.splice(z3, 1);
alert("Contact deleted");
}
if (z == -1) {
alert("Contact not present");
}
}
function searchcon() {
var lenn1 = BOOK.length;
if (lenn1 == 0) {
alert("ADDRESS BOOK EMPTY");
return;
}
var coname = prompt("Enter name");
var ind = BOOK.indexOf(coname);
if (ind >= 0) {
alert("contact found");
return;
}
else {
alert("Contact not present in address book");
}
}
</script>
</head>
<body>
<div id="mainDiv">
<header id="startHeader">
<p id="headerPara">Welcome to Address Book</p>
</header>
<div id="midDiv">
<form id="submissionForm">
<div class="entryDiv">
<p class="inputType">Name:</p>
<input id="userNam" type="text" class="buttonsClass" placeholder="Enter Your Name" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Number:</p>
<input id="userNo" type="text" class="buttonsClass" placeholder="Enter Your Number" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Address:</p>
<input id="userAdd" type="text" class="buttonsClass" placeholder="Enter Your Address" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Email:</p>
<input id="userEmail" type="email" class="buttonsClass" placeholder="Enter Your Email" required="" />
</div>
<div id="Buttons">
<input id="reset" type="reset" value="Reset" />
<input id="delete" type="button" value="Delete Contact" />
<input id="view" type="button" value="View Book" />
<input id="add" type="submit" value="AddToContacts" />
</div>
</form>
<div id="hiddenDiv">
</div>
</div>
</div>
</body>
</html>
Change add button's type "submit" to "button" then remove return statement from add function as it is not needed.
This code has many issues.
You don't need four array to store address detail. you can make one array that can have objects containing the address information.eg.
var Address=function(name,address,email,mobile){
this.name=name;
this.address=address||"not available";
this.email=email||"not available";
this.mobile=mobile;
}
var AddressBook=new Array();
//Adding data in address book
AddressBook.push(new Address("jhon","baker street","a#in.com","049372497"))
You can use jquery to get value of element instead of pure javascript. eg.
var conname = document.getElementById('userNam').value;
//instead of this use jquery
var conname=$("#userNam").val(); // recommended approach
There is no need to calculate array length everywhere.To check duplicate mobile number you can write a function.
there are many other improvement you can have in code. for more examples go through Jquery site and Github public repositories.
Fiddle Demo
Change the <input id="add" type="submit" value="AddToContacts" /> to type="button". type="submit" will refresh the page to form's action and will reset all variables including BOOK.

string validation in jquery/javascript as MM:ss not HH:MM:ss

i want to validate a certain string that a jquery function receives.
here's what i have made so far
var duration=$('#duration').val();
if(//string validation?) {
$('.alert-box').html('Please use the correct format');
}
the string format the i want is mm:ss (its a duration m for minutes and s for seconds)so if a user just enter m:ss or mm:s or if the user entered a single digit minute or second, it should be preceded by a zero like if its 9:00 then it should be 09:00.
this is the latest code i've tried and its still not validating
$('#btnAddTestCat').click(function () {
var code = "addTestCat";
var test_cat=$('#test_cat').val();
var duration=$('#duration').val();
var sub_cat=$('#sub_cat').val();
var e = $('.alert-box');
e.slideUp(300);
if(!(/[0-5][0-9]:[0-5][0-9]/g).test(duration)){
e.html('Please use the correct format!');
return false;
}
var dataString = 'test_cat=' + test_cat + '&duration=' + duration + '&sub_cat=' + sub_cat + '&code=' + code;
$.ajax({
type: "POST",
url: "controller/category_controller.php",
data: dataString,
cache: false,
success: function(result){
var result = $.trim(result);
if(result=='success'){
e.removeClass("alert");
e.addClass("info");
e.html('Category added!');
e.slideDown(300);
e.delay(500).slideUp(300);
}else{
e.removeClass("info");
e.addClass("alert");
e.html(result);
e.slideDown(300);
e.delay(500).slideUp(300);
}
}
});
});
Use this Regex : for mm:ss
if(!(/^(?:[0-5][0-9]):[0-5][0-9]$/).test(duration)){
$('.alert-box').html('Please use the correct format');
}
DEMO
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Test</title>
<script src="/script/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$('#Submit').click(function(){
var val = $('#Input').val();
var validinput = true;
if(val.length!=5){
validinput = false;
}
for(var i=1; i<=val.length; i++){
if(i!=3 && !(isNumeric(val.substring(i-1,i)))){
validinput = false;
}else if(i==3 && val.substring(i-1,i)!=':'){
validinput = false;
}
}
if (!validinput){
alert(val+" does not match the format mm:ss. Please correct this issue before submitting the form.");
return false;
}else{
alert("It's correct!!");
}
});
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
</script>
</head>
<body>
<input type="text" id="Input" value="" /> Format = mm:ss
<br />
<button type="button" id="Submit">Submit</button>
</body>
</html>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources