Make Javascript write on page after submit button pressed - javascript

Here is a bit of code I have sourced from w3schools which shows that whenever a name is over 10 characters, the page should add a bit of text, in this case, it should add on "hi", but instead, it removes everything from the page and goes onto a new page and only displays "hi". How can I resolve this?
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.write("hi");
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
</body>
</html>

Simply put, don't use document.write(). If you read the nice orange text at the top of the documentation, you'll see why:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
document.write() should only be used while a page is loading, to ouput while it's creating the webpage, and should not be used afterwards. Consider creating a div, and writing to there instead:
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.getElementById('result').innerHTML = 'Fname is > 10!';
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
} else {
alert('Submitted Successfully!');
return false; // Returning false here just for SO Code Snippet
}
}
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
<div id="result"></div>
</form>
Additionally, I notice you're setting submitOK = "true". Javascript does have booleans (See this also). Why not use that instead?
submitOK = true;
if (fname.length < 10) {
alert('Your name should be more than 10 characters');
submitOK = false;
}
if (submitOK) { // Same as "if (submitOK == true)"
//Good to go
}

Related

How do I remove "undefined" when auto-filling a form?

function validate() {
var errMsg = "";
var result = true;
var fname = document.getElementById("fname").value;
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name correctly.\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
function storeBooking(
fname
) {
sessionStorage.fname = fname;
}
function getBooking() {
if (sessionStorage.fname != undefined) {
document.getElementById("confirm_fname").textContent = sessionStorage.fname;
}
}
function prefillcard()
{
document.getElementById("fname").value = sessionStorage.fname;
}
window.addEventListener("DOMContentLoaded", prefillcard);
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
<form action="apply.html" method="post" id="regform">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<input type="submit" value="Apply">
</form>
I've set up some code to auto-fill a form if the user had already filled the form in the same browser session and then revisited the form. The only problem is that there is a placeholder, which you need to delete before putting in an input, is there and I don't know how to get rid of it. "Undefined" comes up when you fill the form in the first time. How do I get rid of this?
Note: no jQuery or inline JavaScript.
To store values in session use
window.sessionStorage.setItem("Name", Value));
and to retrieve value from session use
window.sessionStorage.getItem("Name");
Sample code below
function prefillcard() {
if (window.sessionStorage.getItem("fname")) {
var fnm = window.sessionStorage.getItem("fname");
document.getElementById("fname").value = fnm;
}
}
and to set Session value use
var fnm = document.getElementById("fname").value;
window.sessionStorage.setItem("fname", fnm));

email validation accept two dot just in the form

my problem is I want The email should have no spaces in it and the domain name should be either two words separated by a ‘.’ or three words separated by two dots e.g. username#abc.efg.xy.
and not acceptable to more than three dot
<form name="myForm" onsubmit="return validateForm()" method="post" >
Name: <input type="text" name="fname" placeholder="Name">
<br>
Email: <input type="text" name="femail" placeholder="saleh#gmail.com">
<br>
Message: <input class="filed" type="text" size="60" style="height:200px">
<br>
Age : <input type="text" name="fage" placeholder="between 10 and 120">
<br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["femail"].value;
var z = document.forms["myForm"]["fage"].value;
if (x == "" || x == null || y == "" || z == null) {
alert("You must be filled out");
return false;
}
if (isNaN(z) || z < 10 || z > 120) {
alert("the age should be between 10 and 120 ");
return false;
}
if (!y.includes('#') ) { // i do not how to complete the if condition
alert("The emali not include # or more one . ");
return false;
}
}
</script>
your're in for a ride
You can use a regular expression to test if the input is an email, NOTE the following answer tests true to 99.9% of the email addresses, but could still fail
const emailReg = new RegExp(/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.){1,2}[a-zA-Z]{2,}))$/)
if (emailReg.test(y)){
//do something if the email is indeed an email
}
I added some examples in a regex validator https://regex101.com/r/vJ7A3N/1/
source: https://emailregex.com/
you could also use <input type="email" id="email" name="email">

JS Function is invoked but no result

When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>

Getting JavaScript validation to work with PHP

<?php
if (isset($_POST['submit']) ) {
//send to database
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function validateForm() {
var usernameentry = document.forms["registrationform"]["username2"].value;
var passwordentry = document.forms["registrationform"]["password2"].value;
var nameentry = document.forms["registrationform"]["password2"].value;
var emailentry = document.forms["registrationform"]["email"].value;
var atpos = emailentry.indexOf("#");
var dotpos = emailentry.lastIndexOf(".");
if (usernameentry.length < 3 || username.length > 20){
alert("Username must be inbetween 4 and 20 characters");
return false;
}
else if (passwordentry.length < 3 || password.length > 20){
alert("Password must be inbetween 4 and 20 characters");
return false;
}
else if (nameentry.length < 3 || name.length > 45){
alert("Name must be inbetween 4 and 45 characters");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailentry.length || emailentry.length > 154) {
alert("Not a valid e-mail address");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form name="registrationform" method="post" action="login.php" onsubmit="return validateForm();">
Name: <input type="text" name="name"/>
<br/>
<br/>
Email: <input type="text" name="email"/>
<br/>
<br/>
Username: <input type="text" name="username2"/>
<br/>
<br/>
Password: <input type="password" name="password2"/>
<br/>
<br/>
<input type = "submit" name = "submit" value = "submit" />
<br/>
<br/>
</form>
</body>
I want the contents of the if statement to run ONLY when the form has been validated with JavaScript, it runs regardless of whether the value returns is true or false.
I'm guessing what I need to do is similar to
if (isset($_POST['submit']) && onsubmit == true)
Obviously that's not right, but I don't know how to do it.
I know validating with php is a much more logical approach, but I need to demonstrate use of JavaScript.
You don't need to do that. When the form is validated, it will be sent to login.php
You can see this question HTML/Javascript: Simple form validation on submit
Also, there are a lot of libraries which could help you
http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

validation of input text field in html using javascript

<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.

Categories

Resources