Email verfication html and javascript - javascript

below is my code mainly for "Email Validation" but for some reason its not working properly i have no idea why , so do you mind taking a look please. thanks
I guess the main problem is with that line document.getElementById("custEmail").onchange = chkEmail; for some reason chkEmail is a problem...and also the search part myEmail.value.search(+#[a-zA-Z_]+?.[a-zA-
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Web Assignment 1 :Online shopping form</title>
<script type = "text/javascript">
function chkEmail() {
var myEmail = document.getElementById("custEmail");
var pos = myEmail.value.search(+#[a-zA-Z_]+?.[a-zA-Z]{2,6});
if (pos != 0) {
alert("The email you entered (" + myEmail.value +
") is not in the correct form. \n" +
"The correct form is: " +
"whatever#whatever.xxx\n" +
"Please fix it");
myEmail.focus();
myEmail.select();
return false;
} else
return true;
}
</script>
</head>
<body>
<h1> Please fill in the information below </h1>
<form action=""
>
<p>
<h2> Contact Info...</h2>
<pre>
Last Name : <input type="text" name="name2" size="20">
Email : <input type="email" id = "custEmail" onchange ="chkEmail();" size="30">
Mobile number : <input type="text" name="mob" size="15">
</pre>
<input type = "reset" id = "reset" />
<input type = "submit" id = "submit" />
</p>
</form>
<script type = "text/javascript">
<!--
// Set form element object properties to their
// corresponding event handler functions
document.getElementById("custEmail").onchange = chkEmail;
// -->
</script>
</body>
</html>

If you just want a client side validation, why don't you just simply validate using HTML regular expression as follows:
If you just want a client side validation, why don't you just simply validate using HTML regular expression as follows:
<form action="">
<p>
<h2> Contact Info...</h2>
<pre>
Last Name : <input type="text" name="name2" size="20">
Email : <input type="email" id = "custEmail" size="30" pattern="[^#]+#[^#]+\.[a-zA-Z]{2,6}">
Mobile number : <input type="text" name="mob" size="15">
</pre>
<input type = "reset" id = "reset" />
<input type = "submit" id = "submit" />
</form>
See fiddle here:
http://jsfiddle.net/9gthN/

Related

javascript code not working with html script

hi guys I just begin to learn javascript recently and I came across an issue, when I enter a "10" as the first input element and click submit, it should print a "10" at the bottom of the html page, but instead it prints nothing.
<html>
<head>
<head>
<form action="" method="POST" id="info">
<br>Age:<br><label>
<input name="age" id="age" type="text" placeholder= "enter your age" />
</label>
<br>Sex:<br><label>
female<input name="female" id="female" type="checkbox" />|
male<input type="checkbox" name="male" id="male" />|
</label>
<br>weight:<br><label>
<input type="text" name="weight" id="weight" placeholder="enter your weight in kg" />
</label>
<input type="submit" form="info" value="Submit" onclick="validation()"/>
</form>
<div id="div1"> </div>
<script src = "test.js"></script>
<html>
This is the html code (index.html)
function validation(){
var ageinput = parseInt(document.getElementById("age"));
var femaleinput = ducument.getElementById("female");
var maleinput = ducument.getElementById("male");
var weight = parseInt(document. getElementById("weight"));
var formulaformale;
var formulaforfemale;
var gendererror;
if (ageinput == 10){
gendererror = ageinput
}
document.getElementById("div1").innerHTML = gendererror;
}
this is the javascript code.(test.js)
I tried to find syntax errors but everything looks fine to me, I also compared my code with other people's and I could find anything in my code that is different.I am totally new in javascript so I might have missed certain part of the programming language. please help.
Your button type is submit, so it will always submit and reload the page every time you press the button. Make it a normal button by changing input type to button
<input type="button" form="info" value="Submit" onclick="validation()"/>
Then follow #Ibra answer
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;
Try again like this :
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;

Using Javascript To Show Values From HTML

I'm trying to create a HTML Page with multiple forms, and I would like
to show the values from the form on the same page (wiping the original HTML), but after using the button, nothing shows up (the page like reloaded)
Here's the code for HTML :
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender = document.getElementById('gender').value;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = document.getElementById('genderM').value;
} else if (document.getElementById('genderF').checked) {
gender = document.getElementById('genderF').value;
}
document.writeIn("<h3>Thank You! Here's Your Precious Data! </h3>"); document.writeIn("<p> Your Name Is : </p>" + fname + lname); document.writeIn("<p> Gender : " + gender); document.writeIn("<p> Birthday : " + birthday);
document.getElementById('forms').innerHTML = forms;
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results()" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname"> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male"> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"> <br>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</form>
</div>
</body>
</html>
Any ideas what should I do?
Edit : I'm not able to use php or server for this
Your code is riddled with syntax errors: missing parentheses, missing + operators, etc.
document.writeIn (with an uppercase I) is not a function; document.writeln (with a lowercase L) is.
<script> tags aren't self-closing, i.e. you have to write <script src="scriptPage2.js"></script>
document.getElementById('gender') returns null, because there is no element with id="gender".
You're trying to write birthday but you never declared that variable.
I have no idea what you're trying to accomplish with document.getElementById('forms').innerHTML = forms;
In general, you should make use of the browser's built-in debugger to catch all these errors. If you're using Chrome or Firefox, press Ctrl+Shift+I (in IE or Edge, press F12) and open the "Console" tab; you will see all the errors there as the JS parser encounters them.
Once that's all fixed, remove the submit event handler from <form>, and change your submit button like this:
<input id="submit" class="buttonagain" type="button" onclick="Results()" value="Submit!" />
Note the change of type from submit to button. This will prevent the page from reloading, which is the expected behavior when submitting a form.
You don't need the return and ; when calling a js function in html
<form onsubmit="Results()" method="post">
This is your answer.
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = "Male";
} else {
gender = "Female"
}
document.writeln("<h3>Thank You! Here's Your Precious Data! </h3>");
document.writeln("<p> Your Name Is : </p>" + fname + " " + lname);
document.writeln("<p> Gender : " + gender);
document.writeln("<p> Birthday : " + date);
document.getElementById('forms').style.display = "none";
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results();" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname" required> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"required> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male" required> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"required> <br>
</div>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</div>
</form>
</body>
</html>

Dynamically copy input of two fields and paste it in third field?

I'm trying to copy the First Name and Last Name field into another 'Username' field dynamically. The Username field should also be lowercase and have a hyphen in the middle. So for example,
if First Name = John
and Last Name = Smith
then Username (dynamically-created) = john-smith
Any ideas?
You can do this with plain JavaScript. I'm assuming there is a button of some sort to add the fields together. Also assuming that your Input is <input> text boxes.
document.getElementById("button").addEventListener("click", function() {
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var userName = document.getElementById("userName");
userName.value = firstName.toLowerCase() + "-" + lastName.toLowerCase();
});
<input id="firstName" type="text" placeholder="First Name" />
<input id="lastName" type="text" placeholder="Last Name" />
<input id="userName" type="text" placeholder="Username" disabled />
<button id="button">Create Username</button>
To make it dynamically update, use onkeydown or onkeyup. Follow kemotoe's answer.
Another option is using onkeyupevent to make it dynamic. This also takes care of any uppercase letters.
function generateFullName() {
document.getElementById("username").innerText =
document.getElementById("fName").value.toLowerCase() +
"-" +
document.getElementById("lName").value.toLowerCase();
}
First Name <input type="text" id="fName" onkeyup="generateFullName()" />
Last Name <input type="text" id="lName" onkeyup="generateFullName()" /> <br/>
Username: <span id="username" />
You can do it with jquery, too. This is a working example.
Working Fiddle
HTML
<input id = "first"> <br> <br>
<input id = "last"> <br> <br>
<input id = "username">
<button id ="generate">Generate</button>
JS
$("#generate").on("click", () => {
let first = $("#first").val()
let last = $("#last").val()
$("#username").val(first+ "-"+last)
})
$('#firstName').change(updateUsername());
$('#lastName').change(updateUsername());
function updateUsername(){
$('#userName').val($('#firstName').val().toLowerCase() +"-"+$('#lastName').val().toLowerCase() );
}
Bind with change event to update the user name field
You can use the onkeypress event.
It would look like this
document.querySelector('.form').addEventListener(("keypress"), () => {
//Code to edit the username field goes here
//Try pressing a key inside the form
alert('Hi');
});
<form class='form'>
<input type="text">
<input type="text" >
<input type="text" class='username'>
</form>

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Categories

Resources