Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues
I have two text input fields in html and one button. first will take id and second will take password, clicking on button will either display a div saying welcome or a paragraph asking for correct login credentials. the id and password are hard-coded.
Thing is that the submit button is not clickable at all. I don't know what is causing this failure, plz help.
<input type="text" class="id" style="margin-top:10px">
<input type="text" class="pass" style="margin-top:10px">
<button class="enter" style="margin-top:6px; padding:6px; background:orange;">Enter</button>
<p class="loginMsg"></p>
<script>
const idvalue ="Superhero";
const passvalue ="Superzero";
const id = document.querySelector(".id");
const pass = document.querySelector(".pass");
const enter = document.querySelector(".enter");
const para = document.querySelector(".loginMsg");
enter.onclick = function() {
let myid = id.value;
let mypass = pass.value;
if(myid==idvalue && mypass==passvalue) {
let panel = document.createElement("div");
let msgpara = document.createElement("p");
msgpara.textContent="Welcome back "+idvalue;
let btn = document.createElement("button");
btn.textContent = "OK";
panel.appendChild(msgpara);
panel.appendChild(btn);
html.appendChild(panel);
btn.onclick = function(){
panel.parentNode.removeChild(panel);
};
};
else {
para.textContent = "Please enter correct id and password.";
};
};
</script>
Check your code on line 33, you added a semicolon before the else in your if-else statement
if{
...};
else{
};
See https://jsfiddle.net/gfL8jwhq/ for the correction.
Yes due to semicolon(;) after if() condition creating the issue remove it, and it will work properly
enter.onclick = function() {
let myid = id.value;
let mypass = pass.value;
if(myid==idvalue && mypass==passvalue) {
let panel = document.createElement("div");
let msgpara = document.createElement("p");
msgpara.textContent="Welcome back "+idvalue;
let btn = document.createElement("button");
btn.textContent = "OK";
panel.appendChild(msgpara);
panel.appendChild(btn);
html.appendChild(panel);
btn.onclick = function(){
panel.parentNode.removeChild(panel);
};
} else {
para.textContent = "Please enter correct id and password.";
};
};
Good day everyone,
I want my input to validate this formula
function toCelsius(f) {
return (5/9) * (f-32);
}
So that anytime I change the input number, the answer changes. I tried this function, but I am not getting the required solution.
This is what I tried:
put=toCelsius(value);
if (isNaN(x) ) {
text = "Input is not a number";
} else {
text = toCelsius;
document.getElementById("demo1").innerHTML = put;
}
To make your code work, all you have to do is to use addEventListener and bind an event to your form. So I just made a simple form with input and a submit button, then I will listen to the button click after that I will run your provided function (with a bit modification).
So the final output will be something like this:
const input = document.querySelector("input");
const button = document.querySelector("button");
const message = document.getElementById("message");
button.addEventListener("click", toCelsius);
function toCelsius(event) {
event.preventDefault();
const inputValue = input.value;
const toCelsiusValue = (5 / 9) * (inputValue - 32)
if (isNaN(toCelsiusValue) || !inputValue) {
message.innerHTML = "Input is not a number";
} else {
message.innerHTML = ""
input.value = toCelsiusValue
}
}
<div>
<form>
<input type="text">
<button>Convert</button>
</form>
<p id="message"></p>
</div>
I have created a form using bootstrap and am using javascript for form validation and then a php script to grab the post data and display it
the basic structure is the following and I have made this as minimal as I could to address this specific issue. The issue I am having is that the script to check for the form validation works perfectly in the <script> tags at the end of the body, but instead of preventing the page from being submitted as it should it still processes to the next page with the form's contents that are being made through the php post action when the form is indeed not filled out correctly.
Why is this? Should the form validation still not stop the page from moving on to the post data since the validation is returning false if the form has not been submitted correctly. All the form validation alerts pop up correctly and I;m getting no console errors after checking, or do I need to perform an additional check to only process the post data if the form is valid?
<html>
other tags.....
<body>
<form name = "OrderForm" action = "process_order.php" onsubmit = "orderbutton" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
</body>
<script>
function CheckForm() {
var Name = document.getElementById("Name");
var fries = document.forms.OrderForm.FryRadio;
var fryyes = fries[0].checked
var fryno = fries[1].checked
var bool = true;
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked))) {
bool = false;
}
else if (!(fryyes || fryno)) {
bool = false;
}
if (!(bool)) {
alert("Please fill out all of the required fields.");
return false;
}
else {
alert("Your order is being submitted");
console.log("Submitted")
}
};
</script>
</html>
You should call function on submit , I dont know what are you doing with current onsubmit='...'
So use following, call function when you submit the form.
<form name = "OrderForm" action = "process_order.php" onsubmit = "return CheckForm()" method = "post">
a bunch of content, divs, checkboxes, etc
</form>
For demo : Check Fiddle
first of all what you can do is:
you do not need the !fryes in another if statement:
you can do it also in the first if:
if ((Name.value == "" || Name.value == "Name") || (!(document.getElementById("SandwichRadio").checked || document.getElementById("WrapRadio").checked)) || ( (!(fryyes || fryno))) {
bool = false;
}
also what you can do is if bool is false, disable your submit button if there is any?
you can also do an onchange on the texboxes, that way you can validate each text box or checkbox one by one. and have the bool true and false?
I did something like this on jquery long time ago, for validation, where I checked each texbox or dropdown against database and then validate, aswell..
The code is below
<script>
$(document).ready(function(){
var works=true;
//Coding for the captcha, to see if the user has typed the correct text
$('#mycaptcha').on('keyup',function(){
if($('#mycaptcha').val().length>=5){
$.post("user_test/captcha_check.php",
{
// userid: $("#userlogin").val(),
mocaptcha: $("#mycaptcha").val(),
},
function(data,status){
if(data==0){
document.getElementById("final_error").innerHTML="Captcha did not match";
works=false;
}
if(data==1){
works=true;
document.getElementById("final_error").innerHTML="";
}
});
}
});
//Works like a flag, if any mistake in the form it will turn to false
//Coding the submit button...
$('#submitbtn').on('click',function(){
var arrLang = [];
var arrPrf = [];
uid = $("#userid").val();
capc = $('#mycaptcha').val();
pwd = $("#pwd1").val();
fname = $("#fname").val();
lname = $("#lname").val();
email = $("#memail").val();
pass = $("#pwd2, #pwd1").val();
daysel = $('#dayselect').val();
monthsel = $('#monthselect').val();
yearsel = $('#yearselect').val();
agree_term = $('#agree_box').prop('checked');
//checks if the textboxes are empty it will change the flag to false;
if((!uid) || (!capc) ||(!fname) || (!lname) || (!email) || (!pass) || (!daysel) || (!monthsel) || (!yearsel) || (!agree_term)){
works=false;
}
if(!works){
document.getElementById('final_error').innerHTML ="<font size='1.3px' color='red'>Please fill the form, accept the agreement and re-submit your form</font>";
}
else{
works=true;
//A jquery function, that goes through the array of selects and then adds them to the array called arrLang
$('[id=lang]').each(function (i, item) {
var lang = $(item).val();
arrLang.push(lang);
});
//A jquery function, that goes through the array of select prof and then adds them to the array called arrprf
$('[id=prof]').each(function (i, item) {
var prof = $(item).val();
arrPrf.push(prof);
});
var data0 = {fname: fname, mlname : lname, userid : uid,password:pwd, emailid : email, mylanguage : arrLang, proficient : arrPrf, dob : yearsel+"-"+monthsel+"-"+daysel};
//var json = JSON2.stringify(data0 );
$.post("Register_action.php",
{
// userid: $("#userlogin").val(),
json: data0,
},
function(data,status){
if(data==1){
//alert(data);
window.location = 'Registered.php';
}
document.getElementById("userid_error").innerHTML=data;
});
}
});
//to open the agreement in a seperate page to read it..
$("#load_agreement").click(function () {
window.open("agreement.html", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
//A code that loads, another page inside the agreement div
$( "#agreement" ).load( "agreement.html" );
//This part here will keep generating, duplicate of the language and profeciency box, incase someone needs it
$('#Add').click(function(){
//we select the box clone it and insert it after the box
$('#lang').clone().insertAfter("#lang").before('<br>');
$('#prof').clone().insertAfter("#prof").before('<br>');
});
//this part here generates number 1-31 and adds into month and days
i=0;
for(i=1; i<=31; i++){
$('#dayselect').append($('<option>', {value:i, text:i}));
if(i<=12){
$('#monthselect').append($('<option>', {value:i, text:i}));
}
}
//this code here generates years, will work for the last, 120 years
year=(new Date).getFullYear()-120;
i = (new Date).getFullYear()-16;
for(i; i>=year; i--){
$('#yearselect').append($('<option>', {value:i, text:i}));
}
//Regex Patterns
var pass = /^[a-z0-9\.\-\)\(\_)]+$/i;
var uname = /^[a-z0-9\.\-]+$/i;
var mname = /^[a-z ]+$/i;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//When the Last Name texbox is changing this will be invoked
$("#fname").keydown(function(){
//comparing the above regex to the value in the texbox, if not from the box then send error
if(!mname.test($("#fname").val())){
//fill the textbox label with error
document.getElementById("fname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid FirstName</font>";
$("#fname").css("border-color","rgba(255,0,0,.6)");
works=false;
}
else{
$("#fname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("fname_error").innerHTML="";
works = true;
}
});//end of fname onchange
//When the Last Name texbox is changint this will be invoked
$("#lname").keydown(function(){
//comparing the above regex to the value in the texbox
if(!mname.test($("#lname").val())){
//fill the textbox label with error
document.getElementById("lname_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid LastName</font>";
$("#lname").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
$("#lname").css("border-color","rgba(0,255,100,.6)");
document.getElementById("lname_error").innerHTML="";
works = true;
}
});//end of lname on change
//When the userid textbox is chaning,this will be invoked
$("#userid").keydown(function(){
//comparing the above regex to the value in the texbox
if(!uname.test($("#userid").val())){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid UserId</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
works=false;
}
/*
else if($("#userid").val().length<4){
//fill the textbox label with error
document.getElementById("userid_error").innerHTML="<font color='red' size='2px' family='verdana'>Minimum user length is 4</font>";
$("#userid").css("border-color","rgba(255,0,0,.6");
//disable the submit button
//$('#submitbtn').attr('disabled','disabled');
works=false;
}
*/
else{
$("#userid").css("border-color","rgba(0,0,0,.3)");
$.post("user_test/user_email_test.php",
{
// userid: $("#userlogin").val(),
userid: $("#userid").val(),
},
function(data,status){
document.getElementById("userid_error").innerHTML=data;
});
works = true;
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#memail").keydown(function(){
//comparing the above regex to the value in the texbox
if(!emailReg.test($("#memail").val())){
//fill the textbox label with error
document.getElementById("email_error").innerHTML="<font color='red' size='2px' family='verdana'>Invalid Email</font>";
$("#memail").css("border-color","rgba(255,0,0,.6");
works=false;
}
else{
works = true;
$.post("./user_test/user_email_test.php",{
useremail: $("#memail").val(),
},
function(data,status){
document.getElementById("email_error").innerHTML=data;
$("#memail").css("border-color","rgba(0,255,0,.3)");
works = true;
});
}
});//end of change
//When the userid textbox is chaning,this will be invoked
$("#pwd2").keyup(function(){
//checking length of the password
if($("#pwd2").val().length<10){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Please enter a password minimum 10 characters</font>";
//$('#submitbtn').attr('disabled','disabled');
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
works=false;
}
//checking if the password matches
else if($("#pwd1").val()!=$("#pwd2").val()){
document.getElementById("pwd_error").innerHTML="<font color='red' size='2px' family='verdana'>Passwords do not match</font>";
//$('#submitbtn').attr('disabled','disabled');
works=false;
$("#pwd1, pwd2").css("border-color","rgba(0,255,100,.6)");
}
else{
$("#pwd1, #pwd2").css("border-color","rgba(0,0,0,.3)");
document.getElementById("pwd_error").innerHTML="";
//comparing the above regex to the value in the texbox and checking if the lenght is atleast 10
if(!pass.test($("#pwd2").val())){
//fill the textbox label with error
document.getElementById("pwd_error").innerHTML="<font color='red' size='1px' family='verdana'>Your password contains invalid character, Please use: a-z 0-9.( )_- only</font>";
$("#pwd1, #pwd2").css("border-color","rgba(255,0,0,.6");
works = false;
}
else{
$("#pwd1 , #pwd2").css("border-color","rgba(0,255,100,.6)");
works = true;
}
}
});//end of change
});//end of document ready
</script>
I am trying to learn JavaScript, PHP and some basic client-side form validations in trying to build this basic JavaScript tutorial that interacts with PHP and HTML. WHat I am trying to do is interrupt a form submission event, i.e. user forgets to enter a valid email format in the email submission input and clicks on the submit button which should then display an error message and not allow the form to be submitted. But I can't get this to work for me. What happens is that I am instead taken to the support_process.php page when that should not happen. Any help at all would be greatly appreciated.
Here is my index.html code for the form:
<div>
<form id="frmSupport" name="frmSupport" method="post" action="support_process.php">
<fieldset id="fastSupport">
<legend><strong>Fast Support</strong></legend>
<p>If you've already booked the Singing Rails Girls coach,</br> and have not gotten a confirmation number,</br> drop us a line and we'll respond within 24 hours.</p> </p>
<p>
<label for="email">Email:</label>
<input type="text" value="your email" name="name" id="email" tabindex="10" />
<p>
<span id="errorMsg"></span>
</p>
<input type="submit" value="Submit">
</p>
<p><b>Ed's "Blah Blah Blah" Tour Status</b></p>
<label for="tourStatus" class="inline">
<input type="radio" name="tour status" value="booked" id="tourStatus_0" tabindex="40" />Ed already toured here
</label>
<label for="tourConf" class="inline" >
<input type="radio" name="tour conf" value="paid" id= "tourStatus_1" tabindex="50" />Ed confirmed his tour date
</label>
</br>
</fieldset>
</form>
</div>
Comments Section
Comments:
<script src="myscript.js">
</script>
And here is my corresponding JavaScript file:
//alert("Hello, world!"); // this is a JavaScript alert button //
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro...");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
// Handling the form submit event
document.getElementById("frmSupport").onsubmit = function(){
//prevent a form from sumbitting if no email.
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers();
// This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White- Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 5000);
myImage.onclick = function() {
clearInterval(intervalHandle);
}
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
And here is my corresponding php file for the event interrupter (for refusing to allow the form to be submitted if user leaves email field blank or something):
<?php
//some php script can go here
echo "This is the support confirmation page...sorry, nothing fancy here!"
?>
<h1>Thank you, we will contact you shortly!</h1>
<a href="index.html" target="_blank" >Back</a>
<?php
// More php code can go here, and so forth and so on..
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_GET); */
error_log(message);
?>
Here's a problem:
if (document.getElementById("email").value == "") {
document.getElementById(errorMsg).innerHTML = "OOPS!";
//to stop the form from submitting:
return false;
}else {
//reset and allow form submission:
document.getElementById("errorMsg").innerHTML = "";
return true;
}
In the first part of the if, you're trying to get a reference to the errorMsg element using a non-existent variable:
document.getElementById(errorMsg).innerHTML = "OOPS!";
In the second, you're accessing the element by its id properly:
document.getElementById("errorMsg").innerHTML = "";
You need to surround 'errorMsg' with single or double quotes.
You should definitely look into using a debugger to help you find problems like these. Chrome Developer Tools are a good place to start.