Javascript function to validate form AND display css loading screen - javascript

I'm a javascript newbie and I'm attempting to combine two pieces of code which are working individually but not together:
Validate my form to check that the length, width and height are non-zero
If form is valid, submit form and display a css splash loading screen while the content loads
Here is my unsuccessful attempt:
<script type = "text/javascript">
function notEmpty(elem, helperMsg){
if (elem.value.length == 0) {
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show() {
if ((notEmpty(document.getElementById('length'), 'Please Enter a Length')==true) &&
(notEmpty(document.getElementById('height'), 'Please Enter a Height')==true) &&
(notEmpty(document.getElementById('weight'), 'Please Enter a Weight')==true)) {
document.getElementById("myDiv").style.display="block";
setTimeout("hide()", 10000); // 10 seconds
}
}
function hide() {
document.getElementById("myDiv").style.display="none";
}
</script>
My form will call show() on form submit. And myDiv is a css loading page element which appears while the page loads. Again, I apologize if my attempt is way off, I am very new to javascript, and would appreciate any advice to point me in the right direction.

In HTML form add onClick="validate(event)" to the submit button:
<form action="someAction">
<input type="text" id="length"/><br/>
<input type="text" id="height"/><br/>
<input type="text" id="weight"/><br/>
<input type="submit" onClick="validate(event)"/>
</form>
<div id="myDiv" style="display: none">Loading....</div>
then try this code:
function validate(e) {
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;//stop the form from submitting before validating
var arr = ['length', 'height', 'weight'],
valid = true,
helperMsg = ['please choose length value', 'please choose height value', 'please choose weight vale'];
for (var i in arr) {
var elm = document.getElementById(arr[i]);
if (elm.value.length == 0) {
alert(helperMsg[i]);
elm.focus();
valid = false;
break;//stop looping and move to the next step
}
}
if (valid) {
var div = document.getElementById('myDiv');
document.getElementsByTagName('form')[0].submit();//submit the first form, or you can change it to document.getElementBY('id') instead if you add an id to your form which would be better.
div.style.display = 'block';//show div
setTimeout(function () {
div.style.display = 'none';//hide div after 10 sec
}, 10000);
}
}
DEMO

The following is a working solution(may not be the best or ideal), that should work for you as well. Try attaching the function to the submit button. Make it type 'button' attach the 'show' to its click event and modify the 'show' method slightly as shown below. Hope this helps:
<html>
<head>
<script type = "text/javascript">
function notEmpty(elem, helperMsg){
if (elem.value.length == 0) {
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function show() {
if ((notEmpty(document.getElementById('length'), 'Please Enter a Length')==true) &&
(notEmpty(document.getElementById('height'), 'Please Enter a Height')==true) &&
(notEmpty(document.getElementById('weight'), 'Please Enter a Weight')==true)) {
document.getElementById("myDiv").style.display="block";
setTimeout("hide()", 10000); // 10 seconds
document.getElementById("myform").submit();
}
}
function hide() {
document.getElementById("myDiv").style.display="none";
}
</script>
</head>
<body>
<form id="myform" action="someAction" onSubmit="show()">
<input type="text" id="length"/>
<input type="text" id="height"/>
<input type="text" id="weight"/>
<input type="button" value="submit" id="mySubmitBtn" onClick="show()"/>
</form>
<div id="myDiv"></div>
</body>
</html>

Related

How can i submit a fom when their is multiple functions are created , which function to call on evnets like onclick and onsubmit?

<html>
<body>
<form onsubmit="return myFunction()">
<input type="text" id="txt">
<input type="text" id="txt1">
<input type="button" value="click" id="btn">
</form>
</body>
<script>
var a = document.getElementById("txt");
var b = document.getElementById("txt1");
var save = document.getElementById("btn");
//save.addEventListener("click" , myFun);
save.onclick = function(){myFunction()};
//save.addEventListener("click" , myFunction);
function myFunction(){
if((a.value=="") || (b.value=="")){
alert("fill something");
return false;
}else{
alert("all ok");
location.href="sec.html";
return true;
}
//a.addEventListener("keyup" , myFun);
//b.addEventListener("keyup" , myFun);
}
a.addEventListener("keyup" , myKeyFun);
b.addEventListener("keyup" , myKeyFun);
function myKeyFun()
{
if(a.value!==b.value){
alert("mismatched");
return false;
}else{
return true;
}
}
</script>
</html>
i have created many function for different - different validation so now i want to submit the form and redirect to another page when all the cinditons are true.
but here form is getting submitted even when the conditions are not true, i have wrote this code just to understand.
the actual code is quite big so i have wrote this to understand how i would have to call the main function to submit the form when there is multilpe function
Don't mess by making different functions. Do it with conditions as below.
var a = document.getElementById("txt");
var b = document.getElementById("txt1");
var save = document.getElementById("btn");
function myFunction() {
if(a.value == ""){
alert("Please fill Text 1");
}else if(b.value == ""){
alert("Please fill Text 2");
}else if (a.value != b.value){
alert("Text 1 and Text 2 must be same");
}
else{
alert("Successfully submitted");
//redirect to another page code;
}
}
function textTwoFun(){
if(a.value != b.value){
alert('Value missmatched! Text 1 and Text 2 must be same');
}
}
<form>
<input type="text" id="txt" placeholder="Text 1">
<input type="text" id="txt1" onkeyup="textTwoFun()" placeholder="Text 2">
<input type="button" onclick="myFunction()" value="click" id="btn">
</form>

Form Validation Vanilla JS

I'm building a multipage form and I have some unusual validation requirements. Here's what I'd like to do/what I have done so far.
What I Want to Do:
(1) As each form field is filled in, I want a function to run and check that the user-input has met certain conditions -- i.e. for first and last name, that there are no numbers and there is a space in between the names.
(2) Once each of the field are full and have passed as true, I want another function to run that re-enabled a previously disabled "Next" button that will move the user to the next page of the form.
What I Have Done
(1) Created a mini version of the form with two inputs:
One that takes a first name, a space and a last name
One that takes a phone number set up the following way xxx xxx xxx
(2) I've console.logged the results with pass/fail logic so I know when certain things are being input by the user, that the code is validating properly.
Where I am Stuck:
I do not know how to create the secondary code that will reenabled the previously disabled "next" button that will move the form to the next page.
What I would like to do is make it so when the "Next" button is reenabled, and clicked on, it's own onclick function hides the current page, looks for the next page in the sequence and changes its display:block and I believe I have that code worked out separately, but I don't know how to integrate it with my other needs.
function checkForm()
{
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
function checkFirstName()
{
if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
console.log("Put a first Name and Last Name");
}
else
{
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber()
{
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
{
console.log("Please Put in a proper phone number");
}
else
{
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
};
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
See below code.
It might be more user-friendly to use on keyup rather than onblur, as most users I know will try and click the disabled button, rather than pressing tab or focusing on another element.
function checkForm() {
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var phoneCanSubmit, nameCanSubmit = false;
function checkFirstName() {
if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
nameCanSubmit = false;
console.log("Put a first Name and Last Name");
} else {
nameCanSubmit = true;
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber() {
if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
phoneCanSubmit = false;
console.log("Please Put in a proper phone number");
} else {
phoneCanSubmit = true;
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
if (nameCanSubmit && phoneCanSubmit) {
document.getElementById("myButton").disabled = false;
} else {
document.getElementById("myButton").disabled = true;
}
};
<form>
First Name:
<input type="text" id="name" onblur="checkForm()" />
<label id="nameErrorPrompt"></label>
<br />Phone Number:
<input type="text" id="phone" onblur="checkForm()" />
<label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
The code below gives you what you want. I removed some extraneous checks to simplify the code and also moved the event handlers from he HTML to the JavaScript. I also pulled the field checks out of the larger checkForm function. This provides you the flexibility to use them one at at time if need be.
window.addEventListener('load', function(e) {
var nameInput = document.getElementById('name');
var phoneInput = document.getElementById('phone');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(e) {
e.preventDefault(); //Stop the page from refreshing
getNextPage('Next page shown!!');
}, false);
nameInput.addEventListener('blur', function(e) {
checkName(this.value);
}, false);
phoneInput.addEventListener('blur', function(e) {
//Uncomment below to make this responsible only for checking the phone input
//checkPhoneNumber(this.value);
/*You could do away with diasbling and check the form
on submit, but if you want to keep the disable logic
check the whole form on the blur of the last item*/
checkForm();
}, false);
}, false);
function getNextPage(foo) {
console.log('Callback fired: ', foo);
//Do something here
}
function checkPhoneNumber(phone) {
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
console.log("Please Put in a proper phone number");
return 0;
}
else {
console.log("Thank you name entered");
return 1;
}
};
//Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
function checkName(firstAndLastName) {
if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
console.log("Put a first Name and Last Name");
return 0;
}
else {
console.log("Thank You phone entered");
return 1;
}
};
function checkForm() {
var validCount = 0;
fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
var phoneNum = document.getElementById('phone').value;
var name = document.getElementById('name').value;
var myButton = document.getElementById('myButton');
validCount += checkPhoneNumber(phoneNum);
validCount += checkName(name);
console.log(validCount + ' of ' + fieldCount + ' fields are valid');
if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs
myButton.disabled = false;
}
else {
myButton.disabled = true;
}
}
HTML
<form>
First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
How about you start by making the onblur for each input return a boolean indicating if the field is valid.
Then setting a cansubmit variable (= checkName && checkPhone) in the checkForm function and only moving on after that - then you don't need to enable and disable the button.
If you really want the button to enable you can use the same pattern, but do
document.getElementById("myButton").disabled = !canSubmit;
and you will always want to call checkForm on field blur like you are now.
Also note you aren't scoping canSubmit locally right now.

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

Check if every elemnt from a form is filled JQUERY

I have a form with all types of form elemnts and I have a code that should run through every single one of the elemnts and check their value after the submit button is clicked. Unfortunatelly, this code doesn't work completely. What I mean is that if I don't enter any value in the input, it will print the message, but if I enter some text in it, we go to the else statement, without checking the other.
Could somebody tell me why?
if($('form.registration-form :input').val() == '')
{
// Print Error Message
}
else
{
// Do something else
}
You can use filter method for this:
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
// all IS filled in
} else {
// all is NOT filled in
}
$('#submit').click(function(){
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
alert('All Filled');
} else {
alert('1 or more not filled')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" class="registration-form">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="submit" id="submit" value="Check">
</form>

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

Categories

Resources